Mar 29, 2004 22:00
Today was one of those days when I felt like an amateur when it came to shell scripting. In a mailing list I am on a question about if there was a way to get the CIDR notation from ipconfig. For those not in the know, CIDR notation looks like this 10.102.103.2/16 where the 10.102.103.2 is the IP address and the /16 denotes the network bits.
Anyway the rule from RFC is that the netmask has to be contiguous. With that being fact I came up with this:
#!/bin/sh
convert()
{
case ${1} in
255)
VAL=8
;;
254)
VAL=7
;;
252)
VAL=6
;;
248)
VAL=5
;;
240)
VAL=4
;;
224)
VAL=3
;;
192)
VAL=2
;;
128)
VAL=1
;;
0)
VAL=0
;;
*)
echo "Problem"
exit 1
;;
esac
}
getCidr()
{
CIDR=0
for i in 1 2 3 4 ; do
O=`echo ${MASK} | awk -F. -v oct=${i} '{print $oct}'`
convert ${O}
CIDR=`expr $CIDR + $VAL`
done
}
White it isn't the cleanest shell script it served the purpose. I thought it was fairly handy. Well that was until someone else (Dagmar d'Surreal) on the mailing list posted this:
cidrequiv() {
local netmask=$1
local IFS="."
local index=32
set $netmask
local longint=$(( ( $1 << 24 ) + ( $2 << 16 ) + ( $3 << 8 ) + $4 ))
until (( longint & 1 )); do
longint=$(( longint >> 1 ))
(( index -= 1 ))
done
return $index
}
For those not familiar the second way is what I would consider much more elegant. Made me feel like an amateur. Oh well, I learned something today that will help me in the future and I guess that is the point.