¿Hay un script disponible para convertir una dirección IP inicial y final a una notación de barra diagonal?

Ejemplo:

>>> 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
0
paragbaxi 14 jul. 2011 a las 21:27

3 respuestas

La mejor respuesta

Utilice summarize_address_range() de ipaddress , que forma parte de la biblioteca estándar de Python 3 (y respaldado en 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')]
1
Jon-Eric 2 dic. 2019 a las 17:19

La biblioteca ipaddr-py de Google tiene un método llamado summaryize_address_range (primero, último).

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.
"""
1
paragbaxi 15 jul. 2011 a las 13:48

Otra solución:

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)
1
malioboro 28 feb. 2017 a las 16:14