[英]How to calculate end IP in the range, based on start IP and network mask length
我有一個起始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網絡掩碼長度。
這個給你。 我已將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
解決方法很簡單:
// 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地址,這是一個很好的解決方案。 否則,您需要對128位整數函數使用IPv6或從中使用IPv6代替ip2long / long2ip。 但是,對於上面的MaxMind數據代碼來說,使用它們已經足夠了,因為我還沒有看到它們中的任何實際IPv6數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.