使用PHP和CIDR计算IP范围 [英] calculate IP range using PHP and CIDR

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

问题描述

我在这个网站上看到了各种各样的问题和答案,但是仍然很难解决这个问题(可能是因为我感冒了)。无论如何,我都试图提供一个小型Web应用程序,该应用程序将为我们每个办公室创建IP地址表。

I've seen various questions and answers around this site and I'm still having difficulty wrapping my head around this problem (could be because I've got a cold). Regardless, I'm trying to come up with a small web app that will create tables of IP addresses for each of our offices.

比如说,如果我创建一个新的作用域对于10.1.10.0/4,它将创建一个数组(然后可以将其打印到表中):

Like say if I create a new scope for 10.1.10.0/4 it will create an array (which I can then print to a table) of:

 10.1.10.0 network ID
 10.1.10.1 gateway
 10.1.10.2 usable
 10.1.10.3 broadcast

(不是它会自动插入说明,但这就是我们要做的事情。)。

(not that it would insert the descriptions automatically but that's what we'd be doing).

我很确定我会

推荐答案

如前所述,所有IPv4地址都可以使用 ip2long()转换为数字,然后使用 long2ip()转换回数字。我不确定您是否已经注意到,最关键的一点是顺序IP与顺序号相对应,因此您可以操纵这些数字!

As you've already noted, all IPv4 addresses can be converted to numbers using ip2long(), and converted back using long2ip(). The critical extra bit I'm not sure you've noticed is that sequential IPs correspond with sequential numbers, so you can manipulate these numbers!

给出CIDR前缀(例如, $ prefix = 30 ),则可以使用位移运算符

Given a CIDR prefix (e.g, $prefix = 30 for your range), you can calculate the number of IPs in that range using a bit shift operator:

$ip_count = 1 << (32 - $prefix);

然后使用以下方法遍历该范围内的所有IP:

And then loop through all the IPs in that range using:

$start = ip2long($start_ip);
for ($i = 0; $i < $ip_count; $i++) {
    $ip = long2ip($start + $i);
    // do stuff with $ip...
}

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

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