Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of IP addresses in Python to a list of CIDR

Tags:

python

ip

cidr

How do I convert a list of IP addresses to a list of CIDRs? Google's ipaddr-py library has a method called summarize_address_range(first, last) that converts two IP addresses (start & finish) to a CIDR list. However, it cannot handle a list of IP addresses.

Example:
>>> list_of_ips = ['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.5']
>>> convert_to_cidr(list_of_ips)
['10.0.0.0/30','10.0.0.5/32']
like image 530
paragbaxi Avatar asked Jul 15 '11 14:07

paragbaxi


1 Answers

in python3, we have a buildin module for this: ipaddress.

list_of_ips = ['10.0.0.0', '10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.5']
import ipaddress
nets = [ipaddress.ip_network(_ip) for _ip in list_of_ips]
cidrs = ipaddress.collapse_addresses(nets)
list(cidrs)
Out[6]: [IPv4Network('10.0.0.0/30'), IPv4Network('10.0.0.5/32')]
like image 57
Wang Avatar answered Sep 29 '22 19:09

Wang