Glam Prestige Journal

Bright entertainment trends with youth appeal.

I have an input file with IPv4 addresses:

94.228.16.0 - 94.228.25.255
94.241.136.0/24
94.241.136.0 - 94.241.136.255
94.29.128.0/17
94.29.128.0 - 94.29.191.0
94.29.192.0 - 94.29.255.0
94.74.181.0/24
94.74.181.0 - 94.74.181.31
94.74.181.128 - 94.74.181.255

How I can convert the address ranges to netmasks? The result should be:

94.228.16.0/21
94.241.136.0/24
94.241.136.0/24
94.29.128.0/17
94.29.128.0/19
94.29.192.0/19
94.74.181.0/24
94.74.181.0/27
94.74.181.128/25
3

2 Answers

First you will need to install a package to do the conversion

sudo apt install ipcalc

Now you can do it with this little script (please note that it doesn't work if you quote the variable):

$ while read line; do if [[ $line = *-* ]]; then (ipcalc $line | sed '2!d'); else echo $line; fi; done < file
94.228.16.0/21
94.241.136.0/24
94.241.136.0/24
94.29.128.0/17
94.29.128.0/19
94.29.192.0/19
94.74.181.0/24
94.74.181.0/27
94.74.181.128/25

or more readably

while read line; do if [[ $line = *-* ]]; then (ipcalc $line | sed '2!d') else echo $line fi
done < file
1

Perhaps not surprisingly, there is a CPAN perl module Net::CIDR for this.

So for example:

$ perl -MNet::CIDR=range2cidr -lne 'print for range2cidr $_' yourfile
94.228.16.0/21
94.228.24.0/23
94.241.136.0/24
94.241.136.0/24
94.29.128.0/17
94.29.191.0/32
94.29.128.0/19
94.29.160.0/20
94.29.176.0/21
94.29.184.0/22
94.29.188.0/23
94.29.190.0/24
94.29.255.0/32
94.29.192.0/19
94.29.224.0/20
94.29.240.0/21
94.29.248.0/22
94.29.252.0/23
94.29.254.0/24
94.74.181.0/24
94.74.181.0/27
94.74.181.128/25

The module is available on Ubuntu by installing the libnet-cidr-perl package.

NB I have not validated your input or the results.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy