Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ipv4

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
like image 432
paragbaxi Avatar asked Dec 21 '25 06:12

paragbaxi


2 Answers

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')]
like image 59
Jon-Eric Avatar answered Dec 22 '25 18:12

Jon-Eric


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.
"""
like image 30
paragbaxi Avatar answered Dec 22 '25 20:12

paragbaxi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!