IP Range to CIDR conversion in Python?

前端 未结 2 1932
暖寄归人
暖寄归人 2020-12-29 07:05

How can I get a CIDR notation representing a range of IP addresses, given the start and end IP addresses of the range, in Python? I can find CIDR to IP Range but cannot find

2条回答
  •  难免孤独
    2020-12-29 07:44

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

提交回复
热议问题