Netmask calculation with (n)awk

I needed a script to calculate a netmask in dotted decimal notation from the number of bits. Here’s how I did it:

echo "22" | \
nawk '{num=$1;
for (i=1; i=8) printf ("255");
else if (num<=0) printf ("0");
else printf ("%s", 256-2^(8-num));
if (i<=3) printf (".")
num-=8
}
printf ("\n")
}'

or:

nawk 'BEGIN{num=22;
for (i=1; i=8) printf ("255");
else if (num<=0) printf ("0");
else printf ("%s", 256-2^(8-num));
if (i<=3) printf (".")
num-=8
}
printf ("\n")
}'

BTW there are a number of other resources on the web which you might use for this purpose, e.g. this link).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: