IP range for converting CIDR to Python?

How can I get the CIDR notation representing a range of IP addresses, given the starting and ending IP addresses of the range, in Python? I can find the CIDR for the IP range, but I can not find the code for the opposite.

An example of the desired result:

startip = '63.223.64.0' endip = '63.223.127.255' return '63.223.64.0/18' 
+6
source share
2 answers

You can use iprange_to_cidrs provided by netaddr . Example:

 cidrs = netaddr.iprange_to_cidrs(startip, endip) 

Here are the official docs: https://netaddr.readthedocs.io/

+11
source

Running Python 3.3 in the ipaddress bundle can provide what you want. The summarize_address_range function returns an iterator with the networks obtained from the beginning, at the end you specify:

 >>> startip = ipaddress.IPv4Address('63.223.64.0') >>> endip = ipaddress.IPv4Address('63.223.127.255') >>> [ipaddr for ipaddr in ipaddress.summarize_address_range(startip, endip)] [IPv4Network('63.223.64.0/18')] 
+2
source

Source: https://habr.com/ru/post/970821/


All Articles