将 ipv4 网络掩码转换为 cidr 格式

convert ipv4 netmask to cidr format

我有 ip 和网络掩码

192.168.1.0 255.255.255.0

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

192.168.1.0/24

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

我正在使用 PHP5.6

复杂的方法是将网络掩码转换为二进制并计算前导 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);

有点抓住主题,但可能会帮助其他人,而您在这里找到了解决方案:

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

我修复了 php ip2long help0.0.0.0 掩码的代码并稍微简化了它(不需要总是计算 $base = ip2long('255.255.255.255');):

function mask2cidr($mask)
{
    if($mask[0]=='0')
        return 0;

    return 32 - log(~ip2long($mask) + 1, 2);
}

@Barmar 的回答也很好,因为它总是能在任何 PC 架构上完成工作而不会出现任何意外。

以下代码将掩码转为二进制,将二进制转为CIDR

    public function mask2cdr($mask) {
          $dq = explode(".",$mask);
          for ($i=0; $i<4 ; $i++) {
             $bin[$i]=str_pad(decbin($dq[$i]), 8, "0", STR_PAD_LEFT);
          }
          $bin = implode("",$bin); 

          return strlen(rtrim($bin,"0"));
    }
function convert($ip,$mask){
  return $ip."/".strlen(str_replace("0","",decbin(ip2long($mask))))
}