note 35700 deleted from function.ip2long by didou
| From: | didou@php.net | Date: | Fri, 12 Mar 2004 11:06:59 +0000 |
| Subject: | note 35700 deleted from function.ip2long by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-66707@lists.php.net to get a copy of this message | ||
Note Submitter: mkr@binarywerks.dk
----
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);
?>