How to iterate all IP addresses in network using Python
The following code will iterate over all IP addresses in the given network, i.e. 192.168.1.0 ... 192.168.1.254
:
import ipaddress
network = ipaddress.ip_network('192.168.1.0/24')
for ip in network:
print(ip)
The following variant will iterate over all IP addresses in this network except the broadcast IP address 192.168.1.255
and the network IP address 192.168.1.0
:
import ipaddress
network = ipaddress.ip_network('192.168.1.0/24')
for ip in network:
# Ignore e.g. 192.168.1.0 and 192.168.1.255
if ip == network.broadcast_address or ip == network.network_address:
continue
print(ip)