简体   繁体   中英

PHP snippet to match wildcarded IPv4 strings

I'm finding an hard time in figuring out how to create a snippet that can tell me if an ip is matching with a database of blacklisted ips, also containing wildcards. Example:

$global_blacklistedips = Array ( '10.10.*.*', '192.168.1.*' );

function checkBlacklistedIp ( $ip ) {

    // some kind of regular expression

    // match? return true;
    // else return false;
}

Anyone can help? The only approach I've figured out is to code a very very ugly "state machine" that switches between 1, 2, or 3 wildcards ( 4 wildcards would lead to blacklist everything ), but this kind of coding is really a mess

How about something like this:

function to_regex($ip) {
    return '/^' . str_replace(array('*', '.',), array('\d{1,3}','\.'), $ip) . '$/';
}

$global_blacklistedips = array_map('to_regex', $global_blacklistedip);

function checkBlacklistedIp ($ip, $global_blacklistedips ) {
    foreach($global_blacklistedips as $bip) {
        if(preg_match($bip, $ip)) {
           return true; 
        }
    }
    return false;
}

This will first convert all your black list IPs into a regular expression. The function then loops over those and tries to match them.

You can also write your IPs from the beginning as regular expressions, you just need to escape the dot . and replace * with eg \\d{1,3} :

array('10\.10\.\d{1,3}\.\d{1,3}', '192\.168\.1\.\d{1,3}');

You also need delimiters, but you could add them later, like preg_match('#^' + $bid + '$#', $ip) ;

\\d+代替*并使用preg_match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM