读取具有 IP 范围的文件,并查看提供的 IP 是否与文件中的任何范围匹配


read file with ip range and see if supplied IP matches any range in file

我正在尝试读取具有ip/掩码范围的文件,如果提供的IP与文件中的任何范围匹配,它将返回TRUE或类似函数。这是我在下面的代码

function myip2long($ip) {  
   if (is_numeric($ip)) {  
       return sprintf("%u", floatval($ip));  
   } else {  
       return sprintf("%u", floatval(ip2long($ip)));  
   }  
}
function ipfilter($ip) {  
   $match = 0;  
   $ip_addr = decbin(myip2long($ip));  
   if (file_get_contents('./countryip/all-zones/us.zone')) {  
       $source = file('./countryip/all-zones/us.zone');  
       foreach ($source as $line) {  
           $network = explode("/", $line);  
           $net_addr = decbin(myip2long($network[0]));  
           $cidr = $network[1];  
           if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {  
               $match = 1;  
               break;  
           }  
       }  
   }  
   return $match;  
} 
$user_ip = $_SERVER['REMOTE_ADDR'];  
if (ipfilter($user_ip) == 1)  echo "<br />allowed! Your IP is a United States IP!";  
else echo "deny!";

此处提供了一个示例文件(如上例中的文件)http://www.ipdeny.com/ipblocks/data/countries/us.zone

不确定上面的代码是否正确,我从这里得到它'http://www.php.net/manual/en/function.ip2long.php#86793

也许你应该添加一些调试代码,只是为了了解发生了什么。

就像这样:

if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {  
   echo "My IP: $ip'n";
   echo "IP to check: $network[0]'n";
   echo "CIDR: $cidr'n"
   echo "ip digits, my: $ip_addr, check: $net_addr'n";
   $match = 1;  
   break;  
}

所以你会看到出了什么问题。