Bash - 以 CIDR 表示法转换网络掩码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50413579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:55:25  来源:igfitidea点击:

Bash - Convert netmask in CIDR notation?

bashcidrnetmask

提问by Alex_DeLarge

Example: I have this netmask: 255.255.255.0

示例:我有这个网络掩码:255.255.255.0

Is there, in bash, a command or a simple script to convert my netmask in notation /24?

在 bash 中,是否有一个命令或一个简单的脚本来将我的网络掩码转换为符号 /24?

回答by Sasha Golikov

Example Function for RHEL6/RHEL7:

RHEL6/RHEL7 的示例函数:

IPprefix_by_netmask() {
#function returns prefix for given netmask in arg1
 ipcalc -p 1.1.1.1  | sed -n 's/^PREFIX=\(.*\)/\//p'
}

The Result:

结果:

$ IPprefix_by_netmask 255.255.255.0
/24

In other Linux distributives ipcalc options may differ.

在其他 Linux 发行版中,ipcalc 选项可能不同。

The same function without ipcalc, tested in Solaris and Linux:

没有ipcalc的相同功能,在Solaris和Linux上测试过:

IPprefix_by_netmask() {
    #function returns prefix for given netmask in arg1
    bits=0
    for octet in $(echo | sed 's/\./ /g'); do 
         binbits=$(echo "obase=2; ibase=10; ${octet}"| bc | sed 's/0//g') 
         let bits+=${#binbits}
    done
    echo "/${bits}"
}

回答by agc

  1. Function using subnetcalc:

    IPprefix_by_netmask() {
        subnetcalc 1.1.1.1 "" -n  | sed -n '/^Netw/{s#.*/ #/#p;q}'
    }
    
  2. In pure bash, convert IP to a long octal string and sum its bits:

    IPprefix_by_netmask () { 
       c=0 x=0$( printf '%o' ${1//./ } )
       while [ $x -gt 0 ]; do
           let c+=$((x%2)) 'x>>=1'
       done
       echo /$c ; }
    
  1. 功能使用subnetcalc

    IPprefix_by_netmask() {
        subnetcalc 1.1.1.1 "" -n  | sed -n '/^Netw/{s#.*/ #/#p;q}'
    }
    
  2. 在 pure 中bash,将 IP 转换为长八进制字符串并将其位相加:

    IPprefix_by_netmask () { 
       c=0 x=0$( printf '%o' ${1//./ } )
       while [ $x -gt 0 ]; do
           let c+=$((x%2)) 'x>>=1'
       done
       echo /$c ; }
    

Output of IPprefix_by_netmask 255.255.255.0(either function):

IPprefix_by_netmask 255.255.255.0(任一函数)的输出:

/24

回答by D.Liu

Based on Sasha's answer, this script works with dash(tested with Ubuntu 18.04):

根据 Sasha 的回答,此脚本适用于dash(使用 Ubuntu 18.04 测试):

IPprefix_by_netmask() {
    #function returns prefix for given netmask in arg1
    bits=0
    for octet in $(echo | sed 's/\./ /g'); do 
         binbits=$(echo "obase=2; ibase=10; ${octet}"| bc | sed 's/0//g') 
         bits=$(expr $bits + ${#binbits})
    done
    echo "/${bits}"
}