要查找某个 IP 是否在某个 net/mask 中(非常快)
<?php
function isIPIn($ip,$net,$mask) {
$lnet=ip2long($net);
$lip=ip2long($ip);
$binnet=str_pad( decbin($lnet),32,"0","STR_PAD_LEFT" );
$firstpart=substr($binnet,0,$mask);
$binip=str_pad( decbin($lip),32,"0","STR_PAD_LEFT" );
$firstip=substr($binip,0,$mask);
return(strcmp($firstpart,$firstip)==0);
}
?>
这个函数可以进行压缩,避免一些变量设置,但函数的可读性会降低...
示例代码,用于构建一种基于网络的定位服务
<?php
$n = array ( "192.168.0.0/16" => "TUSCANY",
"192.168.1.0/24" => "- Florence",
"192.168.2.0/24" => "- Pisa",
"192.168.3.0/24" => "- Siena",
"192.168.64.0/21" => "- Tuscan Archipelago",
"192.168.64.0/23" => "--- Elba Island",
"192.168.66.0/24" => "--- Capraia Island",
"192.168.67.0/24" => "--- Giannutri Island");
$myip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
$myip = "192.168.2.33";
$myip = "192.168.65.34";
echo "您的位置:<br />\n";
foreach ( $n as $k=>$v ) {
list($net,$mask)=split("/",$k);
if (isIPIn($myip,$net,$mask)) {
echo $n[$k]."<br />\n"; }
}
?>
等等...