I need to calculate the subnet, having a IP address and net mask in a Solaris machine shell (bash, but could be other).
Some examples:
IP=192.168.100.6, MASK=255.255.255.0 => SUBNET=192.168.100.0
IP=11.95.189.33, MASK=255.255.0.0 => SUBNET=11.95.0.0
IP=66.25.144.216, MASK=255.255.255.192 => SUBNET=66.25.144.192
I have two ways to calculate this:
SUBNET=$((`echo $IP | awk 'BEGIN { FS = "." } ; {print $1}'`&`echo $MASK | awk 'BEGIN { FS = "." } ; {print $1}'`)).\
$((`echo $IP | awk 'BEGIN { FS = "." } ; {print $2}'`&`echo $MASK | awk 'BEGIN { FS = "." } ; {print $2}'`)).\
$((`echo $IP | awk 'BEGIN { FS = "." } ; {print $3}'`&`echo $MASK | awk 'BEGIN { FS = "." } ; {print $3}'`)).\
$((`echo $IP | awk 'BEGIN { FS = "." } ; {print $4}'`&`echo $MASK | awk 'BEGIN { FS = "." } ; {print $4}'`))
and
l="${IP%.*}";r="${IP#*.}";n="${MASK%.*}";m="${MASK#*.}"
subnet=$((${IP%%.*}&${NM%%.*})).$((${r%%.*}&${m%%.*})).$((${l##*.}&${n##*.})).$((${IP##*.}&${NM##*.}))
But I think both of them are a little "dirty". I would like a "cleaner" way to calculate the subnet, easy to understand by other people in my project.
I prefer not to use perl or python, but could be considered.
Assume that you store your ip and mask into two shell variables: $ip
and $mask
:
awk -vip="$ip" -vmask="$mask" 'BEGIN{
split(ip,a, ".");
split(mask,b,".");
for(i=1;i<=4;i++)a[i]=b[i]==255?a[i]:b[i];
printf"SUBNET=";for(i=1;i<=3;i++)printf a[i]".";printf a[4]}'
will give you result in format: SUBNET=xxx.xxx.xxx.xxx
take one example:
kent$ ip="192.168.100.6"
kent$ mask="255.255.255.192"
kent$ awk -vip="$ip" -vmask="$mask" 'BEGIN{split(ip,a, "."); split(mask,b,".");for(i=1;i<=4;i++)a[i]=b[i]==255?a[i]:b[i]; printf"SUBNET=";for(i=1;i<=3;i++)printf a[i]".";printf a[4]}'
SUBNET=192.168.100.192