我有一个起始的IPv4 IP地址5.39.28.128
(或::ffff:5.39.28.128
)和IPv6网络掩码长度122
,如何计算范围内的最后一个IP?
我相信我需要把起始IP转换成二进制,我正在做如下的工作,我不知道从那里到哪里才能得到结束IP。
$ipNumber = ip2long('5.39.28.128');
$ipBinary = decbin($ipNumber);
echo $ipBinary; // 101001001110001110010000000
原因是我正在将CSV格式的MaxMind GeoIP数据库导入到MySQL数据库中(因此如果需要,可以使用MySQL函数)。MaxMind不再提供终端IP,而是提供起始IP和IPv6网络掩码长度。
最佳答案
给你。我已经从this response to another question复制了inet_to_bits
函数。
<?php
function inet_to_bits($inet) {
$inet = inet_pton($inet);
$unpacked = unpack('A16', $inet);
$unpacked = str_split($unpacked[1]);
$binaryip = '';
foreach ($unpacked as $char) {
$binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
}
return $binaryip;
}
function bits_to_inet($bits) {
$inet = "";
for($pos=0; $pos<128; $pos+=8) {
$inet .= chr(bindec(substr($bits, $pos, 8)));
}
return inet_ntop($inet);
}
$ip = "::ffff:5.39.28.128";
$netmask = 122;
// Convert ip to binary representation
$bin = inet_to_bits($ip);
// Generate network address: Length of netmask bits from $bin, padded to the right
// with 0s for network address and 1s for broadcast
$network = str_pad(substr($bin, 0, $netmask), 128, '1', STR_PAD_RIGHT);
// Convert back to ip
print bits_to_inet($network);
输出:
::ffff:5.39.28.191