Search code examples
phpcidr

Break a Large CIDR Block Into smaller Blocks with PHP


I've tried searching the forums and couldn't find this anywhere. Found something that would break a CIDR Block completely apart, but I need 2 functions separately.

The first function would take a CIDR Block that is GREATER than /24 and break it into /24 blocks.

The second function I actually have mostly done, would then break each /24 into its 256 IP addresses. The answer for that can be found here. Exploding given IP range with the PHP

So I am trying to figure how to to create a function that is passed a /23 or larger CIDR block and break it into /24s

Example:
Input: BreakTo24(10.0.0.0/22)

Output:
10.0.0.0/24
10.0.1.0/24
10.0.2.0/24
10.0.3.0/24

EDIT: I realized I didn't post my code attempt, which probably makes this more difficult to help. here is the code:

function BreakTo24($CIDR){
    $CIDR = explode ("/", $CIDR);
    //Math to determine if the second part of the array contains more than one /24, and if so how many.

Solution

  • I have (with some help via IRC) figured out that I was doing this ineffectively and needed to use the ip2long function.

    I tested this, and it performed what I wanted it to. Here is my completed code, hopefully someone will find it useful.

    // Function to take greater than a /24 CIDR block and make it into a /24
    Function BreakTo24($CIDR)
    {
        $CIDR = explode("/", $CIDR); // this breaks the CIDR block into octlets and /notation
        $octet = ip2long($CIDR[0]); //turn the first 3 octets into a long for calculating later
        $NumberOf24s = pow(2,(24-$CIDR[1]))-1; //calculate the number of /24s in the CIDR block
        $OutputArray = array();
        for ($i=-256; $i<256 * $NumberOf24s; $OutputArray[] = (long2ip($octet + ($i += 256)))); //fancy math to output each /24
        return $OutputArray; //returns an array of ranges
    

    }