IP Subnet Range calculator for /24 to /32
| From: | Daevid Vincent | Date: | Sat, 17 May 2003 01:56:37 +0000 |
| Subject: | IP Subnet Range calculator for /24 to /32 | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-148001@lists.php.net to get a copy of this message | ||
Didn't know where to put this, nor did I feel like joining one of the PHP
repositories, so I figured I'd just post it up here. I've seen several
'calculators', but I couldn't find one that did exactly what this does.
Pretty self explanatory. Enjoy. Do what you want. Sell it, make millions,
bring down microsoft, whatever... ;-)
--output--
Calculating 192.168.10.10/29
0 => 192.168.10.9
1 => 192.168.10.10
2 => 192.168.10.11
3 => 192.168.10.12
4 => 192.168.10.13
5 => 192.168.10.14
--output--
<?php
function CalculateSubnetIPs($iprange,$slash)
{
// Written by Daevid Vincent (http://daevid.com)
// This function will return an array of either a negative
error code
// or all possible IP addresses in the given /subnet.
//basic error handling to see if it is generally a valid IP
in the form N.N.N.N
if (
preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/",$iprange) != 1 ) return
array(-1);
$quad = explode(".",$iprange);
reset ($quad);
while (list ($key, $val) = each ($quad)) if ($val < 0 ||
$val > 255) return array(-2);
//we'll only deal with class C ranges /24 to /32 for now.
if ($slash == 32 || $slash == 0) return array($iprange);
//special case
if ($slash == 31) return array(-3); //no useable IPs in
this range.
if ($slash < 24 || $slash > 32) return array(-4);
list($junk,$broadcast,$junk,$network) =
preg_split("/[=\s]/",
ipcalc -b -n $iprange/$slash, -1,
PREG_SPLIT_NO_EMPTY);
//echo "Network: ".$network." Broadcast:
".$broadcast."<BR>\n";
$temp = explode(".",$network);
$begin = intval($temp[3]);
$temp = explode(".",$broadcast);
$end = intval($temp[3]);
//echo "begin: ".$begin." end: ".$end."<BR>\n";
$baseIP = $quad[0].".".$quad[1].".".$quad[2];
$i = 0;
$ip = array();
//subnets do not count the $begin or $end in the range of IP
addresses.
for ($ipquad = ($begin + 1); $ipquad < $end; $ipquad++)
$ip[$i++] = $baseIP.".".$ipquad;
return $ip;
}
$myIP = "192.168.10.45";
$mySlash = "25";
echo "<BR>Calculating ".$myIP."/".$mySlash."<BR>\n";
if (!$IPRange = CalculateSubnetIPs($myIP, $mySlash)){ print
"error\n"; }
reset ($IPRange);
while (list ($key, $val) = each ($IPRange))
{
echo "$key => $val<BR>\n";
}
?>
"Ezekiel 25:17. The path of the righteous man is beset on all sides by the
inequities of the selfish and the tyranny of evil men. Blessed is he who in
the name of charity and goodwill shepherds the weak through the valley of
darkness, for he is TRULY his brother's keeper and the finder of lost
children. And I will strike down upon thee with GREAT vengeance and
FU-U-U-URIOUS anger, those who attempt to poison, and destroy my brothers!
And you will KNOW my name is the Lord, when I lay my vengeance upon thee!"