To find if an IP is in a net/mask (very fast):
<?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);
}
?>
This function can be compacted, avoiding some variable settings, but the function will not be too clear to read...
Example code, used to made a kind of location service network-based:
<?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 "Your position:<br />\n";
foreach ( $n as $k=>$v ) {
list($net,$mask)=split("/",$k);
if (isIPIn($myip,$net,$mask)) {
echo $n[$k]."<br />\n"; }
}
?>
and so on...