Reputation: 4398
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.
Upvotes: 1
Views: 1290
Reputation: 631
My solution does what is actually needed to be done. The Ip and mask are 'and'-ed together. This is what I have used.
assuming, here $ip and $mask are defined shell variables.
awk -vip="$ip" -vmask="$mask" 'BEGIN{
sub("addr:","",ip);
sub("Mask:","",mask);
split(ip,a,".");
split(mask,b,".");
for(i=1;i<=4;i++)
s[i]=and(a[i],b[i]);
subnet=s[1]"."s[2]"."s[3]"."s[4];
print subnet;
}'
compressed:
awk -vip="$ip" -vmask="$mask" 'BEGIN{sub("addr:","",ip);sub("Mask:","",mask);split(ip,a,".");split(mask,b,".");for(i=1;i<=4;i++)s[i]=and(a[i],b[i]);subnet=s[1]"."s[2]"."s[3]"."s[4];print subnet;}'
Works similar to the example given by kent.
Example:
[rahul]$ ip=172.16.232.159
[rahul]$ mask=255.255.254.0
[rahul]$ awk -vip="$ip" -vmask="$mask" 'BEGIN{sub("addr:","",ip);sub("Mask:","",mask);split(ip,a,".");split(mask,b,".");for(i=1;i<=4;i++)s[i]=and(a[i],b[i]);subnet=s[1]"."s[2]"."s[3]"."s[4];print subnet;}'
172.16.232.0
Upvotes: 1
Reputation: 195029
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
Upvotes: 1