I have been working on the hiera data generation / validation process. for generation of certain detail i needed both the ip address in the usual 220.127.116.11 way and cidr way. I had initially asked for both as input, when the user’s came back saying what if i give the subnet information along with the ip address like 18.104.22.168/9 and you can calculate the CIDR information. Sounds right.
I had initially asked for that from the user because i did not know how to calculate thing. But since the user has asked it to be that way, i started to look into how to arrive that value. I had the first clue with me, the user had told to look in to XOR based calculation. I started with a generic search to first understand what it and how to arrive it.
May be my Search fu is not very good or whatever, my search always lead to getting ip ranges / calculating the subnet mask with CIDR, and not how to arrive at the CIDR.
There were a few calculators which gave what i wanted, but did not explain how to arrive at it. but playing around with them and seeing the outputs, i could sense a sort of pattern emerging, then thought i have seen something like this before. Then i remembered that there was a third party package which some other application was using at work. i searched for it and lo and behold python3 has that function built in. not sure if python2 had it or not.
Python3 has this module ipaddress which can be used for ip address related things. so for my use case all i had to do is call the appropriate function and give the ipaddress/subnet information and get the output. I had to set strict argument to False. so that i would take ip address also as part of input instead of proper cidr.
>>> import ipaddress >>> network = ipaddress.IPv4Network("10.25.123.20/20", strict=False) >>> str(network) '10.25.112.0/20' >>>