Fragmento de PHP para que coincida con cadenas IPv4 con comodines

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

preguntado el 09 de enero de 11 a las 01:01

who big is this list going to be? If small: replace * es [0-9]+ and match regexps. If big: make it a tree (4 levels deep) of nested arrays. -

2 Respuestas

Vuelva a colocar la * by \d+ y use preg_match.

Respondido el 09 de enero de 11 a las 04:01

Qué tal algo como esto:

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 . y reemplazar * con 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);

Respondido el 09 de enero de 11 a las 04:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.