下面是一个示例代码,用于比较两个表中的IP与范围:
import ipaddress
def compare_ip_with_range(ip_address, ip_range):
ip_network = ipaddress.ip_network(ip_range)
if ipaddress.ip_address(ip_address) in ip_network:
return True
else:
return False
# 示例数据
table1 = [
{'IP': '192.168.0.1'},
{'IP': '10.0.0.1'},
{'IP': '172.16.0.1'},
]
table2 = [
{'StartIP': '192.168.0.0', 'EndIP': '192.168.0.255'},
{'StartIP': '10.0.0.0', 'EndIP': '10.0.0.255'},
]
for row in table1:
ip = row['IP']
for range_row in table2:
start_ip = range_row['StartIP']
end_ip = range_row['EndIP']
if compare_ip_with_range(ip, f"{start_ip}/{end_ip}"):
print(f"IP {ip} 在范围 {start_ip} - {end_ip} 内")
break
else:
print(f"IP {ip} 不在任何范围内")
以上代码中,compare_ip_with_range
函数接受一个IP地址和一个IP范围作为参数,并使用ipaddress
模块来处理IP和IP网络的比较。在主程序中,我们遍历table1
中的每个IP地址,然后遍历table2
中的每个IP范围,并调用compare_ip_with_range
函数来比较IP是否在范围内。如果在范围内,则输出相应的信息,否则输出IP不在任何范围内的信息。
请注意,以上代码假设IP范围是一个CIDR表示法的IP网络,即以IP地址和网络掩码的形式表示。如果IP范围是以起始IP和结束IP的形式表示,则需要根据实际情况进行适当的修改。