Python 有一个名为 ipaddress 的库。
您可以像这样轻松使用它:
import ipaddress
ip_list = [
'156.13.216.251',
'156.13.216.250'
]
isps = [
{
"techCountry": "ISP",
"techCity": "saint-petersburg",
"techName": "Cahit Eyigunlu",
"adminState": "pr.",
"registrantPostalCode": "e16 1ah",
"telephone": "+443333031000",
"domain": "156.13.216.0"
}
]
# First, I suggest to map the networks to ISPs, otherwise it'll be an O(n) operation
# for every IP.
# We add the /24 to signal a network.
network_to_isp = {isp["domain"] + "/24": isp for isp in isps}
ips_not_found = []
ips_to_isps = {}
for ip in ip_list:
network = ipaddress.IPv4Network((ip, 24), strict=False)
isp = network_to_isp.get(str(network))
if isp is None:
ips_not_found.append(ip)
else:
ips_to_isps[ip] = isp
假设我们不知道网络并希望搜索,以下代码将起作用。
请记住,每个 IPv4 最多可能进行 32 次搜索。由于我们不知道 IP 所在的网络。我们无法绕过它。
import ipaddress
ip_list = [
'156.13.216.251',
'156.13.216.250'
]
isps = [
{
"techCountry": "ISP",
"techCity": "saint-petersburg",
"techName": "Cahit Eyigunlu",
"adminState": "pr.",
"registrantPostalCode": "e16 1ah",
"telephone": "+443333031000",
"domain": "156.13.216.0"
}
]
# First, I suggest to map the networks to ISPs, otherwise it'll be an O(n) operation
# for every IP.
# We assume the network is unknown.
network_to_isp = {ipaddress.ip_address(isp["domain"]): isp for isp in isps}
def iter_supernets(address, *, max_mask=None, min_mask=0):
network = ipaddress.ip_network(address)
return (network.supernet(new_prefix=mask)
for mask in range(max_mask or network.prefixlen, min_mask, -1))
ips_to_isps = {}
for ip in ip_list:
for network in iter_supernets(ip):
isp = network_to_isp.get(network.network_address)
if isp:
ips_to_isps[ip] = isp
break
else:
raise RuntimeError("No ISP found for {}".format(ip))