note 54416 modified in function.ip2long by danbrown

From: Date: Fri, 05 Dec 2008 13:42:38 +0000
Subject: note 54416 modified in function.ip2long by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-147698@lists.php.net to get a copy of this message
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. --was-- A quick and efficient way to compare two IPs with a given mask: <? 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: <? $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: <? $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. http://php.net/manual/en/function.ip2long.php

« previous php.notes (#147698) next »