PHP: Convert CIDR to ipaddress range


This function takes an IP address and CIDR netmask (e.g. 102.68.1.0/25), and calculate IP address range in that netblock.

<?php

/**
 * @author phptuts
 * @copyright 2012
 * @link http://tutorialspots.com/
 */

function cidr2ip($cidr)
{
    $ip_arr = explode('/', $cidr);
    $start = ip2long($ip_arr[0]);
    $nm = $ip_arr[1];
    $num = pow(2, 32 - $nm);
    $end = $start + $num - 1;
    return array($ip_arr[0], long2ip($end));
}
?>

Example:

<? var_dump(cidr2ip('102.68.1.0/25')); ?>

result:

array(2) {
[0]=>
string(10) “102.68.1.0”
[1]=>
string(12) “102.68.1.127”
}

Leave a Reply