用於查找 IP 是否位於網路/遮罩中(速度非常快)
<?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" => "托斯卡尼",
"192.168.1.0/24" => "- 佛羅倫斯",
"192.168.2.0/24" => "- 比薩",
"192.168.3.0/24" => "- 西恩納",
"192.168.64.0/21" => "- 托斯卡尼群島",
"192.168.64.0/23" => "--- 厄爾巴島",
"192.168.66.0/24" => "--- 卡普拉亞島",
"192.168.67.0/24" => "--- 吉安努特里島");
$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"; }
}
?>
等等...