note 54416 added to function.ip2long

From: Date: Sun, 03 Jul 2005 23:09:55 +0000
Subject: note 54416 added to function.ip2long
Groups: php.notes 
Request: Send a blank email to php-notes+get-91379@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.ip2long.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+54416 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54416&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54416&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54416&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54416&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54416&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54416&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+54416&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#91379) next »