Python IP List CIDR List

How to convert IP address list to CIDR list? The ipaddr-py Google library has a method called summaryize_address_range (first, last) that converts two IP addresses (start and end) to a CIDR list. However, it cannot process the 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'] 
+4
source share
6 answers

You can do this on one line using netaddr:

 cidrs = netaddr.ip_range_to_cidrs(ip_start, ip_end) 
+3
source

Install netaddr.

pip install netaddr

Use netaddr functions:

 # Generate lists of IP addresses in range. ip_range = netaddr.iter_iprange(ip_start, ip_end) # Convert start & finish range to CIDR. ip_range = netaddr.cidr_merge(ip_range) 
+6
source

Well, summarize_address_range reduces your problem by dividing your list into consecutive ranges. Given that you can convert IP addresses to integers using

  def to_int (str): struct.unpack ("! i", socket.inet_aton (str)) [0]

it should not be too complicated.

+2
source

Expand CIDR ranges to full IP lists by taking the input ranges file and using netaddr https://github.com/JeremyNGalloway/cidrExpand/blob/master/cidrExpand.py

 from netaddr import IPNetwork import sys if len(sys.argv) < 2: print 'example usage: python cidrExpand.py cidrRanges.txt >> output.txt' with open(sys.argv[1], 'r') as cidrRanges: for line in cidrRanges: ip = IPNetwork(line) for ip in ip: print ip cidrRanges.close() exit() 
+1
source

For the comment made by CaTalyst.X, note that you need to switch to the code for it to work.

It:

 cidrs = netaddr.ip_range_to_cidrs('54.64.0.0', '54.71.255.255') 

You need to become the following:

 cidrs = netaddr.iprange_to_cidrs('54.64.0.0', '54.71.255.255') 

If you use the first code instance, you will get an exception, since ip_range_to_cidrs is not a valid attribute of the netaddr method.

+1
source

in python3, we have a built-in module: 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')] 
0
source

All Articles