首页 文章

将ipv4 netmask转换为cidr格式

提问于
浏览
0

我有ip和netmask

192.168.1.0 255.255.255.0

我需要将网络掩码转换为cidr格式

192.168.1.0/24

如何将ipv4地址和网络掩码转换为cidr格式?

我使用的是PHP5.6

2 回答

  • 1

    复杂的方法是将网络掩码转换为二进制并计算前导1位的数量 . 但由于只有33个可能的值,更简单的方法只是一个关联数组:

    $netmask_to_cidr = array(
        '255.255.255.255' => 32,
        '255.255.255.254' => 31,
        '255.255.255.252' => 30,
        ...
        '128.0.0.0' => 1,
        '0.0.0.0' => 0);
    
  • 0

    有点坚持主题,但可能会帮助别人,你在这里有解决方案:

    function mask2cidr($mask)
    {
      $long = ip2long($mask);
      $base = ip2long('255.255.255.255');
      return 32-log(($long ^ $base)+1,2);
    
      /* xor-ing will give you the inverse mask,
          log base 2 of that +1 will return the number
          of bits that are off in the mask and subtracting
          from 32 gets you the cidr notation */
    }
    

    PHP ip2long help

相关问题