Check if ip is with a network block

From: Date: Wed, 14 Nov 2001 22:25:13 +0000
Subject: Check if ip is with a network block
Groups: php.general 
Request: Send a blank email to php-general+get-74647@lists.php.net to get a copy of this message
Greetings, I'd like to check to see if an ip is within an ip cidr style network block (192.75.242.157 with 192.75.242.0/23). Initially, I started off with some code derived from some perl code that I found (code below). However, the bitmask calcution did not work ( $bitmask = 0xffffffff << (32 - $nbits);) and the hexdec did not appear to support values as bit as 0xffffffff. So I did a bit more research and found a relevant posting on the php mailing list. If the function 'within' works properly it should return true if the ip is within the network block but I cannot seem to get it to work properly. Are there any CIDR/bitwise operator wiz's out there that could help me get this straightened out. Thanks. /Paul Input: remote_ip = 192.75.242.88 cidr = 192.75.242.0/24 Output: ip = -1068764584 start = -1068764672 mask = -16777216 function within ($remote_ip, $cidr) { ## within function checks whether an ip is within a network block ## example with("192.75.242.157", "192.75.242.0/24") ## returns true if ip is within range $ip=ip2long($remote_ip); list ($quad, $nbits) = split ("/", $cidr, 2); $shift_mask = (integer) $nbits; $start=ip2long($quad); $mask = -1<<$shift_mask; return $ip & $start == $mask; } PERL derived code: $cidr = $valid_client; /* db value 192.55.192.0/24 */ list ($quad, $nbits) = split ("/", $cidr, 2); $byte = explode (".", $quad); $address_required = ($byte[0] << 24) | ($byte[1] << 16) | ($byte[2] << 8) | $byte[3]; /* remote host info */ $byte = explode(".", $ip); /* ip from $HTTP_SERVER_VARS['REMOTE_ADDR'] */ $address_client = ($byte[0] << 24) | ($byte[1] << 16) | ($byte[2] << 8) | $byte[3]; $bitmask = 0xffffffff << (32 - $nbits); if (($address_client & $bitmask) == ($address_required & $bitmask)) { echo "Ip is within block"; } else { echo "Ip is NOT within block"; } -- ________________________________________________________________ Paul Wolstenholme SMA Webware http://www.zzube.com/ What do you know? http://make.zzube.com/ Vancouver, BC Canada

« previous php.general (#74647) next »