如何使用 Python 遍历网络中的所有 IP 地址
以下代码将遍历给定网络中的所有 IP 地址,即 192.168.1.0 ... 192.168.1.254:
iterate_ips_basic.py
import ipaddress
network = ipaddress.ip_network('192.168.1.0/24')
for ip in network:
print(ip)以下变体将遍历此网络中的所有 IP 地址,除了广播 IP 地址 192.168.1.255 和网络 IP 地址 192.168.1.0:
iterate_ips_no_broadcast.py
import ipaddress
network = ipaddress.ip_network('192.168.1.0/24')
for ip in network:
# 忽略例如 192.168.1.0 和 192.168.1.255
if ip == network.broadcast_address or ip == network.network_address:
continue
print(ip)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow