note 63778 modified in function.ip2long by danbrown
| From: | danbrown@php.net | Date: | Fri, 05 Dec 2008 13:36:27 +0000 |
| Subject: | note 63778 modified in function.ip2long by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-147689@lists.php.net to get a copy of this message | ||
Here is a script that will calculate host range and number of hosts with a given ip address CIDR
notation (modified code which was posted by phl AT cyways.com):
<?php
$ip_addr_cidr = "192.168.37.215/27";
$ip_arr = explode('/', $ip_addr_cidr);
$bin = '';
for($i=1;$i<=32;$i++) {
$bin .= $ip_arr[1] >= $i ? '1' : '0';
}
$ip_arr[1] = bindec($bin);
$ip = ip2long($ip_arr[0]);
$nm = ip2long($ip_arr[1]);
$nw = ($ip & $nm);
$bc = $nw | (~$nm);
echo "Number of Hosts: " . ($bc - $nw - 1) . "\n";
echo "Host Range: " . long2ip($nw + 1) . " -> " . long2ip($bc - 1) .
"\n";
?>
This will produce:
Number of Hosts: 30
Host Range: 192.168.37.193 -> 192.168.37.222
--was--
Here is a script that will calculate host range and number of hosts with a given ip address CIDR
notation (modified code which was posted by phl AT cyways.com):
$ip_addr_cidr = "192.168.37.215/27";
$ip_arr = explode('/', $ip_addr_cidr);
$bin = '';
for($i=1;$i<=32;$i++) {
$bin .= $ip_arr[1] >= $i ? '1' : '0';
}
$ip_arr[1] = bindec($bin);
$ip = ip2long($ip_arr[0]);
$nm = ip2long($ip_arr[1]);
$nw = ($ip & $nm);
$bc = $nw | (~$nm);
echo "Number of Hosts: " . ($bc - $nw - 1) . "\n";
echo "Host Range: " . long2ip($nw + 1) . " -> " . long2ip($bc - 1) .
"\n";
This will produce:
Number of Hosts: 30
Host Range: 192.168.37.193 -> 192.168.37.222
http://php.net/manual/en/function.ip2long.php