Reputation: 13
I Want to iterate over some IP address and networks, to check if an IP belongs to a particular network.
This is what I have written so far.
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)
This is my expected output.
IP_found -> ['172.17.34.2', '172.17.35.1']
IP_miss -> ['172.17.33.1', '172.17.36.2']
I got the below output:
['172.17.34.2', '172.17.35.1']
['172.17.34.2', '172.17.33.1']
Upvotes: 1
Views: 287
Reputation: 707
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)
Try this instead.
Upvotes: 1