PHP Generate IP Ranges
Asked Answered
R

3

7

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

Repel answered 28/8, 2012 at 22:27 Comment(0)
M
15

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) );
Mediate answered 28/8, 2012 at 22:33 Comment(0)
M
3

How about this:

$range_one = "1.1.1.1";
$range_two = "1.1.3.5";
$ip1 = ip2long ($range_one);
$ip2 = ip2long ($range_two);
while ($ip1 <= $ip2) {
    print_r (long2ip($ip1) . "\n");
    $ip1 ++;

}

Update:

BTW, your expected output isn't exactly a range. For instance, the next IP after 1.1.1.1 is 1.1.1.2 and not 1.1.2.2.

Mayramays answered 28/8, 2012 at 22:29 Comment(2)
you have to see the result yourself, it ends up with like infinity results and not like how i mentioned, also.. it ignores the given second rangeRepel
See the update to the answer, its not infinity. Your expected output was missing several IP addresses in the range.Mayramays
W
-1

You may use inet_ntop, inet_ pton http://www.php.net/manual/en/function.inet-ntop.php

Witchhunt answered 28/8, 2012 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.