Python ipaddress 模块,collapse_addresses() 实例源码

我们从Python开源项目中,提取了以下2个代码示例,用于说明如何使用ipaddress.collapse_addresses()

项目:telepresence    作者:datawire    | 项目源码 | 文件源码
def covering_cidr(ips: List[str]) -> str:
    """
    Given list of IPs, return CIDR that covers them all.

    Presumes it's at least a /24.
    """

    def collapse(ns):
        return list(ipaddress.collapse_addresses(ns))

    assert len(ips) > 0
    networks = collapse([
        ipaddress.IPv4Interface(ip + "/24").network for ip in ips
    ])
    # Increase network size until it combines everything:
    while len(networks) > 1:
        networks = collapse([networks[0].supernet()] + networks[1:])
    return networks[0].with_prefixlen


# Script to dump resolved IPs to stdout as JSON list:
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
def spanning_network(networks):
    if not networks:
        raise ValueError("List of networks is empty")
    if len(networks) == 1:
        return networks[0]

    sorter = operator.attrgetter("num_addresses")
    while True:
        networks = sorted(
            ipaddress.collapse_addresses(networks), key=sorter, reverse=True)

        if len(networks) == 1:
            return networks[0]

        networks[-1] = networks[-1].supernet()