dtz8044 2012-04-09 07:26
浏览 22
已采纳

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

I am trying to read a file with ip/mask ranges and if the supplied IP matches any range in the file it will return with TRUE or similar function. Here is the code I have below

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!";

An example file (like the one in the example above) is available here http://www.ipdeny.com/ipblocks/data/countries/us.zone

Not sure if the code above is correct, I got it from here' http://www.php.net/manual/en/function.ip2long.php#86793

  • 写回答

1条回答 默认 最新

  • dqp21271 2012-04-09 09:11
    关注

    Probably you should add some debug code, just to understand what is going on.

    Just like this:

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

    So you'll see what is going wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么