Search code examples
pythonipv4

Convert an IPv4 range (start and end) to slash notation in Python?


Is there a script available to convert a starting and ending IP address to a slash notation?

Example:

>>> ip_long = '10.182.71.0-10.182.75.255'
>>> convert_to_slash(ip_long)
10.182.71.0/24, 10.182.72.0/22

Solution

  • Use summarize_address_range() from ipaddress, which is part of the Python 3 standard library (and backported to Python 2).

    >>> import ipaddress
    >>> first = ipaddress.IPv4Address('10.182.71.0')
    >>> last = ipaddress.IPv4Address('10.182.75.255')
    >>> summary = ipaddress.summarize_address_range(first, last)
    >>> list(summary)
    [IPv4Network('10.182.71.0/24'), IPv4Network('10.182.72.0/22')]