paragbaxi
paragbaxi

Reputation: 4223

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

Upvotes: 3

Views: 2997

Answers (3)

Jon-Eric
Jon-Eric

Reputation: 17275

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

Upvotes: 6

Mozarlelle
Mozarlelle

Reputation: 11

Another solution:

from ipaddress import IPv4Address, summarize_address_range

a=" ".join(map(str, summarize_address_range(IPv4Address('8.8.8.8'), IPv4Address('8.8.9.1'))))

print(a)

Upvotes: 1

paragbaxi
paragbaxi

Reputation: 4223

Google's ipaddr-py library has a method called summarize_address_range(first, last).

summarize_address_range(first, last):
"""Summarize a network range given the first and last IP addresses.

Example:
    >>> summarize_address_range(IPv4Address('1.1.1.0'),
        IPv4Address('1.1.1.130'))
    [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
    IPv4Network('1.1.1.130/32')]

Args:
    first: the first IPv4Address or IPv6Address in the range.
    last: the last IPv4Address or IPv6Address in the range.

Returns:
    The address range collapsed to a list of IPv4Network's or
    IPv6Network's.

Raise:
    TypeError:
        If the first and last objects are not IP addresses.
        If the first and last objects are not the same version.
    ValueError:
        If the last object is not greater than the first.
        If the version is not 4 or 6.
"""

Upvotes: 1

Related Questions