Getting list IPs from CIDR notation in PHP

TamTam picture TamTam · Feb 8, 2011 · Viewed 22.3k times · Source

Is there a way (or function/class) to get the list of IP addresses from a CIDR notation?

For example, I have 73.35.143.32/27 CIDR and want to get the list of all IP's in this notation. Any suggestions?

Thank you.

Answer

jonavon picture jonavon · May 2, 2011

I'll edit the aforementioned class to contain a method for that. Here is the code I came up with that might help you until then.

function cidrToRange($cidr) {
  $range = array();
  $cidr = explode('/', $cidr);
  $range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1]))));
  $range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1);
  return $range;
}
var_dump(cidrToRange("73.35.143.32/27"));

//////////////////OUTPUT////////////////////////
// array(2) {
//   [0]=>
//   string(12) "73.35.143.32"
//   [1]=>
//   string(12) "73.35.143.63"
// }
/////////////////////////////////////////////////

Returns the low end of the ip range as the first entry in the array, then returns the high end as the second entry.