Getting list IPs from CIDR notation in PHP


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

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

Thank you.


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;

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

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

Answered By – jonavon

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published