Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 292
The Governor Avatar asked Dec 11 '14 16:12

The Governor


1 Answers

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'>
like image 103
jamessan Avatar answered Oct 26 '22 11:10

jamessan