如何根据起始IP和网络掩码长度计算范围内的结束IP

时间:2014-05-29 13:11:38

标签: php mysql network-programming ip maxmind

我有一个起始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网络掩码长度。

2 个答案:

答案 0 :(得分:3)

你在这里。我已从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

答案 1 :(得分:2)

解决方案非常简单:

// Your input data
$networkstart = '5.39.28.128';
$networkmask = 122;

// First find the length of the block: IPv6 uses 128 bits for the mask
$networksize = pow(2, 128 - $networkmask);

// Reduce network size by one as we really need last IP address in the range,
// not first one of subsequent range
$networklastip = long2ip(ip2long($networkstart) + $networksize - 1);

$ networklastip将包含该范围内的最后一个IP地址。

现在这仅适用于IPv6地址空间中的IPv4地址。否则,您需要使用IPv6到128位整数函数,而不是ip2long / long2ip。但是,对于MaxMind使用上面的数据代码就足够了,因为我还没有看到任何实际的IPv6数据。

相关问题