代码之家  ›  专栏  ›  技术社区  ›  AlexW

Python比较两个IP列表并返回列表中最低到0的IP条目?

  •  0
  • AlexW  · 技术社区  · 7 年前

    我已经设法编制了两个IP地址列表。已使用和未使用的IP

    unused_ips = ['172.16.100.0/32', '172.16.100.1/32', '172.16.100.2/32', '172.16.100.3/32', '172.16.100.4/32', '172.16.100.5/32', '172.16.100.6/32', '172.16.100.7/32', '172.16.100.8/32', '172.16.100.9/32'...]
    
    used_ips = ['172.16.100.1/32','172.16.100.33/32']
    

    我现在想做的是比较这些列表并返回下一个免费IP。在上面的例子中,下一个ip将是172.16.100.2/32,直到它分发了从1到32的所有ip,然后它将分发34。

    我不知道从哪里开始,如果有内置的东西,我可以将这些转换为IPv4Network对象,但我在文档中找不到任何东西

    谢谢

    3 回复  |  直到 7 年前
        1
  •  3
  •   Robᵩ    7 年前

    我会保持 set 属于 ipaddress 对象并操纵它们来分配和取消分配地址,如下所示:

    import ipaddress
    
    def massage_ip_lists():
        global unused_ips, used_ips
        unused_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
                         for ip in unused_ips)
        used_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
                       for ip in used_ips)
    
    def allocate_next_ip():
        new_ip = min(unused_ips - used_ips)
        used_ips.add(new_ip)
        return new_ip
    
    unused_ips = [
        '172.16.100.0/32',
        '172.16.100.1/32',
        '172.16.100.2/32',
        '172.16.100.3/32',
        '172.16.100.4/32',
        '172.16.100.5/32',
        '172.16.100.6/32',
        '172.16.100.7/32',
        '172.16.100.8/32',
        '172.16.100.9/32']
    used_ips = ['172.16.100.1/32', '172.16.100.33/32']
    
    massage_ip_lists()
    print(allocate_next_ip())
    print(allocate_next_ip())
    

    注:

    • /32 是IP网络的术语,而不是IP主机。
    • IP地址 对象是可比较的,所以函数 min() 对其进行操作。
    • 172.16.100.0 是完全有效的IP地址,具体取决于网络掩码。如果你不想分配它,要么让它远离 unused_ips ,或使程序知道正在使用的网络掩码。
        2
  •  1
  •   jbch    7 年前

    您需要未使用但未使用的IP:

    available_ips = [ip for ip in unused_ips if ip not in used_ips]
    

    您需要对它们进行排序,以得到最接近零的一个。由于您有字符串,简单排序将不起作用;172.16.xxx。xxx排序高于172.100。xxx。例如xxx。您可以将IP转换为数字列表以正确排序。

    import re
    available_ips = sorted(available_ips, key=lambda ip: (int(n) for n in re.split(r'[./]', ip)))
    
        3
  •  0
  •   aknight0    7 年前

    如果您只是尝试遍历可用IP的列表,可以执行以下操作:

    # Filter unavailable ips from the list of all ips
    available_ips = set(unused_ips) - set(used_ips)
    
    # Iterate through list of available ips
    for ip in available_ips:
        print(ip) # Or whatever you want to do with the next available ip