简体   繁体   English

PHP代码段以匹配通配的IPv4字符串

[英]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. 我在弄清楚如何创建一个可以告诉我某个ip是否与列入黑名单的ip的数据库(也包含通配符)的代码段方面遇到了困难。 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 我发现的唯一方法是编写一个非常丑陋的“状态机”,该状态机在1个,2个或3个通配符之间切换(4个通配符会导致将所有内容都列入黑名单),但是这种编码确实是一团糟

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. 这将首先将您所有的黑名单IP转换为正则表达式。 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 . 您也可以从一开始就将IP编写为正则表达式,只需要转义点即可. and replace * with eg \\d{1,3} : 并将*替换为\\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) ; 您还需要定界符,但可以稍后添加它们,例如preg_match('#^' + $bid + '$#', $ip) ;

\\d+代替*并使用preg_match

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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