Home > Back-end >  Calculate which subnets an IP address belongs to
Calculate which subnets an IP address belongs to

Time:10-28

I'm kind of stuck on a particular issue. I need to calculate the subnets an IP address belongs to. It could be done in SQL or Python or similar.

So if I have e.g. 100.100.100.105 I need to get all the subnets:

100.100.100.105/32
100.100.100.104/31
100.100.100.104/30
100.100.100.104/29
100.100.100.96/28
100.100.100.96/27
100.100.100.64/26
...
100.64.0.0/10
100.0.0.0/9
...
64.0.0.0/2
0.0.0.0/1

But really don't know how to approach the issue.

CodePudding user response:

you can achieve this with the python3 built in ipaddress module

import ipaddress
addresses = []
# get the int representation of your ip
ip = int(ipaddress.IPv4Address('100.100.100.105'))

for mask in range(32):
    addresses.append(f'{ipaddress.IPv4Address(ip & ((2**32-1)-(2**mask -1)))}/{32-mask }')

At each iteration, we apply the mask to our IP by doing a logic AND operation between the integer representations of the IP and the mask. We then convert the result to ip octets and append the '/24' subnet notation. You can replace 2**32-1 with 4294967295, I left it there so its clearer what is happening.

  • Related