PHP生成IP范围 [英] PHP Generate IP Ranges

查看:256
本文介绍了PHP生成IP范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何用IP

为例。

  $ range_one =1.1.1.1; 
$ range_two =1.1.3.5;
print_r(范围($ range_one,$ range_two));

/ *我想得到的结果是:
1.1.1.1
1.1.2.2
1.1.3.3
1.1.3.4
1.1。 3.5
* /

我正在考虑使用explode()函数来爆炸。 然后将每个数字分开,然后将它们一起使用范围,然后将它们结合在一起,这对我来说似乎有点复杂,我想有一种更简单的方法来做到这一点。

解决方案

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

  / *生成所有IP地址列表
之间$ start和$结束(包括)。 * /
函数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));


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

解决方案

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

这篇关于PHP生成IP范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆