更新时间:2022-03-19 06:01:21
如前所述,所有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...
}