note 54416 deleted from function.ip2long by cmb
| From: | cmb@php.net | Date: | Sun, 13 Oct 2019 07:46:09 +0000 |
| Subject: | note 54416 deleted from function.ip2long by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212605@lists.php.net to get a copy of this message | ||
Note Submitter: tomlove at gmail dot com
----
A quick and efficient way to compare two IPs with a given mask:
<?php
function ipmatch ($ip1, $ip2, $mask) {
if ((ip2long($ip1) & ~(pow(2, 32-$mask)-1)) == (ip2long($ip2) & ~(pow(2, 32-$mask)-1)))
return true;
else return false;
}
?>
Here's an application of it that selects the best IP given the choice of a (possibly private or
invalid) forwarded address or a (possibly proxy) apparent address:
<?php
$a = $_SERVER['HTTP_X_FORWARDED_FOR'];
if ($a == '' || ipmatch($a, "10.0.0.0", 8) || ipmatch($a,
"172.16.0.0", 12) || ipmatch($a, "192.168.0.0", 16) || ipmatch($a,
"255.255.255.255", 32)) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = $a;
?>
Or use it to ban people:
<?php
$banned_ip = '135.23.12.3';
if (ipmatch($ip, $banned_ip, 32)) die('BANNED!');
?>
The bitwise comparison the function uses can be done in SQL to do ban matches right in your
database.