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?

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more