Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Generate IP Ranges

As you know, range() function can get a range between number and the other,

how to do the same with an IP
as example..

$range_one = "1.1.1.1";
$range_two = "1.1.3.5";
print_r( range($range_one, $range_two) ); 

 /* I want a result of :
     1.1.1.1
     1.1.2.2
     1.1.3.3
     1.1.3.4
     1.1.3.5
 */

i was thinking of using the explode() function to explode " . " and separate each number then use range with each of them after that combine them all together, it seems a bit complicated for me and i guess there's an easier method to do it

like image 236
Osa Avatar asked Aug 28 '12 22:08

Osa


1 Answers

You can use ip2long to convert the IP addresses into integers. Here's a function that works for old IPv4 addresses:

/* Generate a list of all IP addresses
   between $start and $end (inclusive). */
function ip_range($start, $end) {
  $start = ip2long($start);
  $end = ip2long($end);
  return array_map('long2ip', range($start, $end) );
}

$range_one = "1.1.1.1";
$range_two = "1.1.3.5";
print_r( ip_range($range_one, $range_two) );
like image 85
Emil Vikström Avatar answered Oct 10 '22 14:10

Emil Vikström