Example: I have this netmask: 255.255.255.0
Is there, in bash, a command or a simple script to convert my netmask in notation /24?
Function using subnetcalc
:
IPprefix_by_netmask() {
subnetcalc 1.1.1.1 "$1" -n | sed -n '/^Netw/{s#.*/ #/#p;q}'
}
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 ; }
Output of IPprefix_by_netmask 255.255.255.0
(either function):
/24