note 37753 added to ref.network

From: Date: Tue, 25 Nov 2003 14:01:57 +0000
Subject: note 37753 added to ref.network
Groups: php.notes 
Request: Send a blank email to php-notes+get-60973@lists.php.net to get a copy of this message
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"); // Normally you should use the following line $myip = $HTTP_SERVER_VARS['REMOTE_ADDR']; // This is first example: returns Tuscany/Pisa $myip = "192.168.2.33"; // This is second example: returns Tuscany/T.Arch./Elba $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... ---- Manual Page -- http://www.php.net/manual/en/ref.network.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37753 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37753&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37753&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#60973) next »