IP2Location

Posted on

Convert IP address range to CIDR

This is a short tutorial that shows you the core function of how the conversion of IPv4 to CIDR works.

This function, iprange2cidr, takes 2 input parameters, namely the ipStart and ipEnd, the starting and the ending of an IP address respectively.

You can either supply the IP address in dotted format, for example, 202.186.13.4, or IP number, for example, 3401190660, as the input parameters. The function will convert them into IP number if the dotted IP address format was supplied and perform the calculation.

``````<?php
function iprange2cidr(\$ipStart, \$ipEnd){
if (is_string(\$ipStart) || is_string(\$ipEnd)){
\$start = ip2long(\$ipStart);
\$end = ip2long(\$ipEnd);
}
else{
\$start = \$ipStart;
\$end = \$ipEnd;
}

\$result = array();

while(\$end >= \$start){
\$maxSize = 32;
while (\$maxSize > 0){
\$maxSize--;
}
\$x = log(\$end - \$start + 1)/log(2);
\$maxDiff = floor(32 - floor(\$x));

if(\$maxSize < \$maxDiff){
\$maxSize = \$maxDiff;
}

\$ip = long2ip(\$start);
array_push(\$result, "\$ip/\$maxSize");
\$start += pow(2, (32-\$maxSize));
}
return \$result;
}