How to change ip addressing format from CIDR notation to netmask and vice versa?

Hi all, I would appreciate if someone could share how to convert CIDR notation to netmask and vice versa.
The value below is just an example. it could be different numbers/ip addresses.

Initial Output, let say file1.txt

Final Output, let say file2.txt

What's your shell? What's your system?

CIDR to netmask is straightforward if tedious -- just binary math. Shells aren't generally that good at it but modern BASH has large enough numbers to handle this.

#!/bin/bash

while IFS="/" read IP S
do
        M=$(( 0xffffffff ^ ((1 << (32-S)) -1) ))
        echo "$IP netmask $(( (M>>24) & 0xff )).$(( (M>>16) & 0xff )).$(( (M>>8) & 0xff )).$(( M & 0xff ))"
done

If you have an older bash, it may generate negative values due to overflowing its 32-bit integers.

1 Like

Awesome! Thanks Corona688 for the script. It's not what I'm looking for, but the script is good.
Here is my actual question, I've rephrased it and created separate topic for this.

Bumping up posts or double posting is not permitted in these forums.

Please read the rules, which you agreed to when you registered, if you have not already done so.

You may receive an infraction for this. If so, don't worry, just try to follow the rules more carefully. The infraction will expire in the near future

Thank You.

The UNIX and Linux Forums.

1 Like