DEV Community

IP2Location
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){
                $mask = hexdec(iMask($maxSize - 1));
                $maskBase = $start & $mask;
                if($maskBase != $start) break;
                $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;
    }

    function iMask($s){
        return base_convert((pow(2, 32) - pow(2, (32-$s))), 10, 16);
    }

?>
Enter fullscreen mode Exit fullscreen mode

If you are looking for more sample codes in other languages, visit Converting IP address ranges into CIDR format for the full article.


Where can I get free IP Geolocation database?

Top comments (0)