PHP 生成 IP 范围

2022-01-24 00:00:00 function loops range php explode

如你所知,range() 函数可以得到一个数字和另一个之间的范围,

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

如何对 IP 做同样的事情
比如……

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
 */

我正在考虑使用explode()函数来分解."并将每个数字分开,然后将它们中的每一个使用范围,然后将它们组合在一起,这对我来说似乎有点复杂,我想有一个更简单的方法去做吧

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

推荐答案

您可以使用ip2long 将IP地址转换为整数.这是一个适用于旧 IPv4 地址的函数:

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) );

相关文章