download this file: findsubnet-by-input.php view text/plain: findsubnet-by-input.php file encoding: UTF-8 [goback]
<?php
function inet_aton($ipaddr)
{
return sprintf('%u',ip2long($ipaddr));
}
function inet_ntoa($base)
{
return long2ip($base);
}
function inet_ntocidr($netmask)
{
$netmask = trim($netmask);
$bits = decbin(abs(sprintf('%u',ip2long($netmask))));
$cidr = strpos($bits,'0') + 0;
return ($cidr > 0) ? $cidr : 32;
}
## network to pow of bit
##
function inet_ntopow($start, $end, $nn=0)
{
static $_class_b = 2147483648; // inet_aton('128.0.0.0') == start of B class
static $_class_c = 3221225472; // inet_aton('192.0.0.0') == start of C class
static $_all_bit = 4294967295; // inet_aton('255.255.255.255')
if($start < $_class_b) $pow = 1; // is an A class
else if($start < $_class_c) $pow = 8; // is a B class
else
{
if(!$nn)
{
$nn = $start + $_all_bit - $end; // network to int
//$ln = strlen(preg_replace('/^([1]+).*$/','\1',decbin($nn)));
}
$pow = strpos(decbin($nn),"0");
}
return $pow; // integer, pow of bit
}
function _find_subnet($start, $end, $np=0, $nn=0)
{
if(!$np) $np = inet_ntopow($start,$end,$nn);
for($l=$np; $l<=32; $l++)
{
$hbit = 32 - $l;
$host = pow(2,$hbit);
$tbit = str_repeat(1,$l).str_repeat(0,$hbit);
$tnet = bindec($tbit);
$tend = $start + $host - 1;
//echo $l."\n";
if($tend > $end) continue;
$tand = bindec($tbit & sprintf('%032b',$tend));
if($start == $tand)
{
//$nstart = $tend + 1; // change
break;
}
}
return array($tend,$tnet);
}
function mksubnet($start, $end)
{
$r = array();
$np = inet_ntopow($start,$end);
while($start <= $end)
{
list($tend,$mask) = _find_subnet($start,$end,$np);
$ps = inet_ntoa($start);
$pe = inet_ntoa($tend);
$netmask = inet_ntoa($mask);
$cidr = inet_ntocidr($netmask);
echo "$ps\t$pe\t$netmask\t$cidr\n";
$start = $tend + 1; // change
}
return $r; // array
}
$startip = $_SERVER['argv'][1];
$endip = $_SERVER['argv'][2];
$start = inet_aton($startip);
$end = inet_aton($endip);
mksubnet($start,$end);
exit(0);
?>