【问题标题】:may ipaddress.collapse_addresses() collapse for more than 1 bit of the mask?ipaddress.collapse_addresses() 是否可以折叠超过 1 位的掩码?
【发布时间】:2017-09-08 00:11:13
【问题描述】:

为什么会这样:

>>> import ipaddress
>>> print [ip for ip in ipaddress.collapse_addresses([ipaddress.IPv4Network(u'192.0.128.0/24'), ipaddress.IPv4Network(u'192.0.129.0/24')])]
[IPv4Network(u'192.0.128.0/23')]

但是:

>>> print [ip for ip in ipaddress.collapse_addresses([ipaddress.IPv4Network(u'192.0.129.0/24'), ipaddress.IPv4Network(u'192.0.130.0/24')])]
[IPv4Network(u'192.0.129.0/24'), IPv4Network(u'192.0.130.0/24')]

我想要达到的目标:

>>> print [ip for ip in ipaddress.collapse_addresses([ipaddress.IPv4Network(u'192.0.129.0/24'), ipaddress.IPv4Network(u'192.0.130.0/24')])]
[IPv4Network(u'192.0.128.0/22')]

似乎collapse_addresses 不能折叠超过 1 位的掩码。

【问题讨论】:

    标签: python ip-address ipv4


    【解决方案1】:
    import ipaddr
    
    ips = [ipaddr.IPv4Address(ip) for ip in ['10.10.10.0','10.10.11.0']]
    ips = sorted(ips)
    lowest_ip  = ips[0]  #first 
    highest_ip = ips[-1] #last 
    mask_length = ipaddr._get_prefix_length(int(lowest_ip), int(highest_ip), 
    lowest_ip.max_prefixlen)
    network_ip = ipaddr.IPNetwork("{}/{}".format(lowest_ip, mask_length)).network
    network = ipaddr.IPNetwork("{}/{}".format(network_ip, mask_length), strict = True)
    print (network)
    

    $> 10.10.10.0/23

    【讨论】:

      【解决方案2】:

      此函数返回包含 ipv4 网络列表的最小网络:

      ADDRESS_ANY = ip_address(u'0.0.0.0')
      def one_net(subnets):
          """
          Get the one IP network that covers all subnets in input,
          or None is subnets are disjoint.
          """
          if len(subnets) == 0:
              return None
      
          minlen = min([net.prefixlen for net in subnets])
          while subnets.count(subnets[0]) < len(subnets) and minlen > 0:
              # all subnets are not (yet) equal
              subnets = [net.supernet(new_prefix=minlen) for net in subnets]
              minlen -= 1
      
          # 0.0.0.0/? -> no common subnet
          if subnets[0].network_address == ADDRESS_ANY:
              return None
          return subnets[0]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-31
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        相关资源
        最近更新 更多