2016-05-31 155 views
0

我可以使用“ip2long”php方法从ipv4的子网掩码计算cidr。我应该如何计算ipv6相同?计算ipv6 cidr php

例如,

我可以计算如下:

255.255.252.0 => /22 

我应该怎么计算相同像IPv6地址:

ffff:ffff:ffff:ffff:: 
ffff:ffff:ffff:ffff:0:0:0:0 

当我试图对IPv6相同的I没有得到任何输出?

注:我不计算使用此CIDR表示法的IP地址。我只是想将ipv6的子网掩码转换为其相关的网络位。

+2

[从CIDR前缀PHP5计算IPv6的范围?](的可能的复制http://stackoverflow.com/questions/10085266/php5-calculate-ipv6-range-from-cidr-prefix ) –

+0

@TomaszKowalczyk我不在这里计算范围。你所说的重复问题只有相反的解决方案。 –

回答

2
function ip6_mask2cidr($mask) { 
    $s = ''; 
    if (substr($mask, -1) == ':') $mask .= '0'; 
    if (substr($mask, 0, 1) == ':') $mask = '0' . $mask;  
    if (strpos($mask, '::') !== false) 
     $mask = str_replace('::', str_repeat(':0', 8 - substr_count($mask, ':')).':', $mask); 

    foreach(explode(':',$mask) as $oct) { 
     // The following two lines, perhaps, superfluous. 
     // I left them because of the paranoia :) 
     $oct = trim($oct); 
     if ($oct == '') $s .= '0000000000000000'; 
     else $s .= str_pad(base_convert($oct, 16, 2), 16, '0', STR_PAD_LEFT); 
    } 
    return strlen($s) - strlen(rtrim($s, '0')); 
} 

echo ip6_mask2cidr('ffff:ffff:ffff:ffff::') . "\n"; // 64 

demo