我的目标是在Python语言中遍历所有可能用于网络(如计算机、IoT设备等,而不是专用网络)的ipv4地址组合。在我搜索的过程中,我找到了几个解决方案:
1:使用while循环并循环遍历可能的组合(但是,不确定这是否会停止,我从一个现在找不到的C堆栈溢出中移植了它):
i = 0
while(i != -1):
b1 = (i >> 24) & 0xff
b2 = (i >> 16) & 0xff
b3 = (i >> 8) & 0xff
b4 = (i >> 4) & 0xff
i += 12:使用for循环:我在一个bash问题中找到了这段代码:bash - Generate all possible ipv4 addresses using seq
(c代码):
int main() {
int h, i, j, k;
for (h = 0; h < 256; h++) {
for (i = 0; i < 256; i++) {
for (j = 0; j < 256; j++) {
for (k = 0; k < 256; k++) {
printf("%d.%d.%d.%d\n", h, i, j, k);
}
}
}
}
return 0;
}我想知道有没有更好的方法?这两种实现都允许0.0.0.0和私有ips有效,所以目前我不想要这些解决方案。
发布于 2021-10-26 07:57:39
我会修改4个嵌套的循环。这是不完整的,只是基本的想法:
for a in range(1, 224): # skip 0.0.0.0/8 reserved,
# 224.0.0.0/4 multicast, 240.0.0.0/4 reserved
if a == 10:
continue # skip 10.0.0.0/8 private
if a == 127:
continue # skip 127.0.0.0/8 loopback
for b in range(256):
if a == 172 and 16 <= b < 32:
continue # skip 172.16.0.0/12 private
if a == 192 and b == 168:
continue # skip 192.168.0.0/16 private
for c in range(256):
for d in range(1, 255): # omit network x.x.x.0 and broadcast x.x.x.255
pass # now you have a.b.c.d正如我所说的,某些主机地址的有效性取决于网络掩码。有关保留地址的完整列表,请访问:https://en.wikipedia.org/wiki/Reserved_IP_addresses#IPv4
发布于 2021-10-26 06:50:02
你可以使用ipaddress,它在标准库中。is_private将排除RFC1918地址(10.0.0.0/8、172.16.0.0/12、192.168.0.0/16)以及其他一些地址。
import ipaddress
all_ipv4 = ipaddress.ip_network('0.0.0.0/0')
for host in all_ipv4.hosts():
if host.is_private:
continue
print(host) #do your thing herehttps://stackoverflow.com/questions/69718005
复制相似问题