本文介绍了在 PHP 中比较 IP 地址和通配符的优化方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道一种有效且安全的方法来查看此输入:

Anyone know of an effective and secure method to see if this input:

$_SERVER['REMOTE_ADDR']

匹配类似于这个不一致过滤器数组的东西(请注意,200.100.*.* 可以仅表示为 200.100.*),并使用 * 表示的通配符:

matches against something similar to this array of inconsistent filters (note that 200.100.*.* could be expressed as just 200.100.*) with wildcards indicated by *'s:

array(
  '192.168.1.*',
  '192.168.2.1*',
  '10.0.0.*',
  '200.100.*.*',
  '300.200.*',
)

更新

想法?

foreach($instanceSettings['accessControl']['allowedIpV4Addresses'] as $ipV4Address) {
    echo 'Now checking against '.$ipV4Address.'.';

    // Compare each octet
    $ipV4AddressOctets = String::explode('.', $ipV4Address);
    $remoteIpV4AddressOctets = String::explode('.', $_SERVER['REMOTE_ADDR']);
    $remoteIpV4AddressIsAllowed = true;
    for($i = 0; $i < Arr::size($ipV4AddressOctets); $i++) {
        echo 'Comparing '.$ipV4AddressOctets[$i].' against '.$remoteIpV4AddressOctets[$i].'.';
        if($ipV4AddressOctets[$i] != $remoteIpV4AddressOctets[$i] && $ipV4AddressOctets[$i] != '*') {
            echo 'No match.';
            $remoteIpV4AddressIsAllowed = false;
            break;
        }
    }

    // Get out of the foreach if we've found a match
    if($remoteIpV4AddressIsAllowed) {
        break;
    }
}

推荐答案

我没有对此进行基准测试,但我会选择使用网络硬件/软件使用的方法...

I haven't bench-marked this, but I would opt to use the method that networking hardware/software uses...

将任何 * 替换为 0 和 255.将 IP 转换为整数

Replace any * with 0 and 255.Convert the IPs to integers

所以如果 255.255.255.* 变成 255.255.255.0 和 255.255.255.255然后对这两个ip做ip2long函数.

So if 255.255.255.* becomes 255.255.255.0 and 255.255.255.255Then do ip2long function on these two ips.

然后就可以把给定的ip转换成长ip了.例如255.255.50.51变成长ip.

Then you can convert the given ip into long ip. for example 255.255.50.51 into long ip.

然后可以比较这个给定ip的长ip是否在黑名单中转换后的长ip之间.如果是,则不允许,否则不允许.

Then you can compare whether the long ip for this given ip is between the converted long ips in the blacklist. If it is then it is not allowed else it is.

$ips = array("ip1", "ip2");
foreach($ips as $ip){
 $ip1 = str_replace("*", "0", $ip);
 $ip2 = str_replace("*", "255", $ip);

 $ip1 = ip2long($ip1);
 $ip2 = ip2long($ip2);
 $givenip = $_GET["ip"];
 $givenip = ip2long($givenip);

 if($givenip >= $ip1 && $ip <= $givenip){
   echo "blacklist ip hit between {$ip1} and {$ip2} on {$ip}";
 }
}

这篇关于在 PHP 中比较 IP 地址和通配符的优化方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 11:14