IP Range to CIDR conversion in Python?

Starting Python 3.3 the bundled ipaddress can provide what you want. The function summarize_address_range returns an iterator with the networks resulting from the start, end you specify:

>>> import ipaddress
>>> 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')]

You may use iprange_to_cidrs provided by netaddr module. Example:

pip install netaddr
import netaddr
cidrs = netaddr.iprange_to_cidrs(startip, endip)

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

Tags:

Python