note 55230 added to ref.network
| From: | metator at netcabo dot pt | Date: | Thu, 28 Jul 2005 03:22:56 +0000 |
| Subject: | note 55230 added to ref.network | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-92607@lists.php.net to get a copy of this message | ||
Regarding samuele's note:
You can get faster code if you apply directly what happens in network devices, such as routers. If
you AND (logic operation) the remote ip against the local netmask the result will be the network ip
if the remote ip is from the local network. Example:
192.168.0.16 = 11000000.10101000.00000000.00010000
& 255.255.255.0 = 11111111.11111111.11111111.00000000
--------------------------------------------------------------
192.168.0.0 = 11000000.10101000.00000000.00000000
And now the code. My example uses a html form where you place the values you want to test:
<HTML><HEAD><TITLE>Check IP</TITLE>
</HEAD><BODY>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="POST">
Hope you find this useful.
IP to check: <input type="text" name="ip"> <br>
Local network ip: <input type="text" name="net"> <br>
Local netmask: <input type="text" name="mask"> <br>
<input type="submit" name="check" value="Check it!">
</form>
<?php
/**
* @param string $ip IP to check in dotted decimal format
* @param string $net Network IP in dotted decimal format
* @param string $mask Netmask in dotted decimal format
* @returns true if the ip belongs to the network, false otherwise
**/
function isIPIn($ip, $net, $mask) {
//doesn't check for the return value of ip2long
$ip = ip2long($_POST['ip']);
$rede = ip2long($_POST['net']);
$mask = ip2long($_POST['mask']);
//AND
$res = $ip & $mask;
return ($res == $rede);
}
if (isset($_POST['check'])) {
echo isIPIn($_POST['ip'], $_POST['net'], $_POST['mask']) ? "IP
IN.": "IP OUT.";
}
?>
</BODY><HTML>
----
Manual Page -- http://www.php.net/manual/en/ref.network.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+55230
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55230&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55230&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55230&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55230&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55230&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55230&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+55230&report=yes
Search -- http://master.php.net/manage/user-notes.php