我想遍历一些IP地址和网络,以检查IP是否属于特定网络



我想遍历一些IP地址和网络,以检查IP是否属于特定网络。

这是我迄今为止所写的。

import netaddr, ipaddress
from netaddr import *
IP_found = []
IP_miss = []
dca = ['172.17.34.2', '172.17.33.1', '172.17.35.1', '172.17.36.2']
ip_net = [IPNetwork('172.17.34.0/27'), IPNetwork('172.17.35.0/27')]
for element in ip_net:
temp = ipaddress.ip_network(element)
for ip in dca:
if ipaddress.ip_address(ip) in (temp):
IP_found.append(ip)
break
else:
IP_miss.append(ip)
print(len(IP_found))
print(len(IP_miss)) 
print(IP_found)
print(IP_miss)

这是我的预期输出。

IP_found -> ['172.17.34.2', '172.17.35.1']
IP_miss -> ['172.17.33.1', '172.17.36.2']

我得到了以下输出:

['172.17.34.2', '172.17.35.1']
['172.17.34.2', '172.17.33.1']
import netaddr,ipaddress
from netaddr import *
IP_found = []
IP_miss = []
dca = ['172.17.34.2', '172.17.33.1', '172.17.35.1', '172.17.36.2']
ip_net = [IPNetwork('172.17.34.0/27'), IPNetwork('172.17.35.0/27')]
for ip in dca: # Loops through the ip
if any(ip in ip_subnet for ip_subnet in ip_net): # Loops through subnet
IP_found.append(ip) 
else:
IP_miss.append(ip)
print(len(IP_found))
print(len(IP_miss))
print(IP_found)
print(IP_miss)

试试这个。

最新更新