Python 比较两个 IP 列表和 return 列表中最低的 0 IP 条目?

Python compare two lists of IPs and return the lowest to 0 IP entry in list?

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

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

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

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

谢谢

如果您只是想遍历可用 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

我会保留 setipaddress 对象并操纵它们来分配和取消分配地址,如下所示:

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 主机的命名法。
  • ipaddress 对象是可比较的,因此像 min() 这样的函数可以对它们起作用。
  • 172.16.100.0 是完全有效的 IP 地址,具体取决于网络掩码。如果您不想分配它,请将其保留在 unused_ips 之外,或者让程序知道正在使用的网络掩码。

您想要未使用但未使用的 ips:

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