note 35700 added to function.ip2long

From: Date: Thu, 11 Sep 2003 13:41:13 +0000
Subject: note 35700 added to function.ip2long
Groups: php.notes 
Request: Send a blank email to php-notes+get-56149@lists.php.net to get a copy of this message
Here's a function that expands a CIDR notation address into an array of address ranges. Please feel free to correct the code, as it has not been properly tested (it should work though!) Watch out: The array can get rather big if you use a small number after the / <? function expand_CIDR($ip) { // validate IP address $num="([0-9]|1?\d\d|2[0-4]\d|25[0-5])"; $range="([1-9]|1\d|2\d|3[0-2])"; if(preg_match("/^$num\.$num\.$num\.$num\/$range$/",$ip_addr)) { return 0; } // Separate CIDR structure into network-IP and netmask $ip_arr = explode("/",$ip); // Calculate number of hosts in the subnet $mask_bits = $ip_arr[1]; if($mask_bits > 31 || $mask_bits < 0) die("Nonsense mask\n"); $host_bits = 32-$mask_bits; $num_hosts = pow(2,$host_bits)-1; // Netmask in decimal for use later: (hack around PHP always using signed ints) $netmask = ip2long("255.255.255.255")-$num_hosts; // Calculate start and end // Store IP-addresses internally as longs, to ease compare of two // addresses in a sorted structure. $ip_start = ip2long($ip_arr[0]); if($ip_start != ( $ip_start & $netmask )) echo("WARNING: Address $ip not on network boundary\n"); $ip_end = $ip_start + $num_hosts; for($i=0;$i<=$num_hosts;$i++) { $ip_range[]=long2ip($ip_start+$i); } return $ip_range; } // demo code: $ip_range=expand_CIDR("111.111.111.10/28"); print_r($ip_range); ?> ---- Manual Page -- http://www.php.net/manual/en/function.ip2long.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35700 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35700&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35700&report=yes

« previous php.notes (#56149) next »