PHP Creating IP Ranges

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

how to do the same with an IP address as an 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 about using the explode () function to explode the "." and separate each number, and then use the range with each of them, and then combine them all together, for me it is a little difficult, and I think there is an easier way to do this

+5
source share
3 answers

You can use ip2long to convert IP addresses to integers. Here is 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) );
+8
source

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:

, . , IP 1.1.1.1 1.1.1.2, 1.1.2.2.

+3

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

-1
source

All Articles