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?
Example Function for RHEL6/RHEL7:
IPprefix_by_netmask() {
#function returns prefix for given netmask in arg1
ipcalc -p 1.1.1.1 $1 | sed -n 's/^PREFIX=\(.*\)/\/\1/p'
}
The Result:
$ IPprefix_by_netmask 255.255.255.0
/24
In other Linux distributives ipcalc options may differ.
The same function without ipcalc, tested in Solaris and Linux:
IPprefix_by_netmask() {
#function returns prefix for given netmask in arg1
bits=0
for octet in $(echo $1| sed 's/\./ /g'); do
binbits=$(echo "obase=2; ibase=10; ${octet}"| bc | sed 's/0//g')
let bits+=${#binbits}
done
echo "/${bits}"
}