Get the smallest network given a list of IPv4 addreses in Python
Asked Answered
S

1

6

I am using python 2.6.6 and I am not allowed to change it. I have a sorted list of IPv4 addresses. I need to find the smallest network that covers all the ip addresses in the list. The smallest network can be the CIDR, or a Network address with subnet mask. I haven't yet found a simple way to do it using netaddr module. Here's example:

x=['192.168.0.0', '192.168.2.245', '192.168.255.255']
cidr = get_cidr_for_addresses(x)
print cidr ##should print '192.168.0.0/16'
Squalid answered 11/12, 2014 at 16:54 Comment(2)
Why don't you use bitwise operations to figure this out? Turn addresses to bits, find first different bit and take all the preceeding bits as your network and then inverse that number to get the subnet. If you need more info, this might help to visualize it: subnet-calculator.comDeuteragonist
Thanks. Call me lazy but I am looking for a library to do it for me so that I don't have to maintain the code.Squalid
T
9

This seems to be exactly what netaddr.spanning_cidr does.

$ python
Python 2.7.9rc1 (default, Dec 10 2014, 10:58:16)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import netaddr
>>> x = netaddr.spanning_cidr(['192.168.0.0', '192.168.2.245', '192.168.255.255'])
>>> print x
192.168.0.0/16
>>> print type(x)
<class 'netaddr.ip.IPNetwork'>
Thoth answered 11/12, 2014 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.