首页 文章

计算ipv6 cidr php

提问于
浏览
0

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

例如,

我可以计算以下内容:

255.255.252.0 => /22

我应该如何为ipv6地址计算相同的内容,例如:

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

当我尝试相同的ipv6我没有得到任何输出?

Note: 我没有使用此CIDR表示法计算IP地址 . 我只想将ipv6的子网掩码转换为其相关的网络位 .

1 回答

  • 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

相关问题