<?php 
/*
* range2cidr.php
*
* Frédéric LOIRETTE - 2002-2005
*
* http://www.loirette.fr/frederic
*/

if (isset($Source))
{
    
show_source("range2cidr.php");
    exit;
}

function 
imask($ip)
{
    
// use base_convert not dechex because dechex is broken and returns 0x80000000 instead of 0xffffffff
    
return base_convert((pow(2,32) - pow(2, (32-$ip))), 1016);
}

function 
imaxblock($ibase$tbit)
{
    while (
$tbit 0)
    {
        
$im hexdec(imask($tbit-1));
        
$imand $ibase $im;
        if (
$imand != $ibase)
        {
            break;
        }
        
$tbit--;
    }
    return 
$tbit;
}

function 
range2cidrlist($istart$iend)
{
    
// this function returns an array of cidr lists that map the range given
    
$s explode("."$istart);
    
// PHP ip2long does not handle leading zeros on IP addresses! 172.016 comes back as 172.14, seems to be treated as octal!
    
$start "";
    
$dot "";
    while (list(
$key,$val) = each($s))
    {
        
$start sprintf("%s%s%d",$start,$dot,$val);
        
$dot ".";
    }
    
$end "";
    
$dot "";
    
$e explode(".",$iend);
    while (list(
$key,$val) = each($e))
    {
        
$end sprintf("%s%s%d",$end,$dot,$val);
        
$dot ".";
    }
    
$start ip2long($start);
    
$end ip2long($end);
    
$result = array();
    while (
$end $start)
    {
        
$maxsize imaxblock($start,32);
        
$x log($end $start 1)/log(2);
        
$maxdiff floor(32 floor($x));
        
$ip long2ip($start);
        if (
$maxsize $maxdiff)
        {
            
$maxsize $maxdiff;
        }
        
array_push($result,"$ip/$maxsize");
        
$start += pow(2, (32-$maxsize));
    }
    return 
$result;
}


    if (!isset(
$IP1))
        
$IP1 "192.168.0.1"
    if (!isset(
$IP2))
        
$IP2 "192.168.0.255"
    
?>
<HTML>
<HEAD>
<style type="text/css">
<!--
    body,pre,div,span,th,td,input,.s{font-family:arial,helvetica,sans-serif;font-size:12px}
-->
</style>
</HEAD>
<BODY bgcolor="#F5DEB3" text="000000">
Conversion IP NetRange --> CIDR : <BR>
<FORM METHOD=post ACTION="range2cidr.php" ENCTYPE="multipart/form-data" name="CIDR2Range">
    IP&nbsp;:&nbsp;<INPUT TYPE='text' NAME='IP1' VALUE='<?php echo $IP1?>' ACCEPT="text/html" Size="15" MaxLength="15"/>&nbsp;-&nbsp;
    <INPUT TYPE=text NAME="IP2" value="<?php echo $IP2?>"\ ACCEPT="text/html" Size="15" MaxLength="15"/>
    <INPUT TYPE='submit' value='OK'/>
</FORM>
<?php
    
echo "<BR>Calculating ".$IP1." - ".$IP2."<BR>\n"
     
    foreach (
range2cidrlist($IP1,$IP2) as $key => $value)
        echo 
"Cl&eacute;: $key; Valeur: $value<br>\n";

?> 

</BODY></HTML>