【问题标题】:Generate all possible (public internet) IPV4 Address combinations in Python在 Python 中生成所有可能的(公共互联网)IPV4 地址组合
【发布时间】:2021-10-26 16:43:14
【问题描述】:

我的目标是在 Python 中遍历所有可能用于网络(如计算机、物联网设备等,但不是专用网络)组合的 ipv4 地址。 在搜索过程中,我找到了几个解决方案:

1: 使用 while 循环并循环遍历可能的组合(但是,不确定这会停止,我从 C 中的 stackoverflow 中移植了它,但现在找不到):

i = 0
while(i != -1):

    b1 = (i >> 24) & 0xff
    b2 = (i >> 16) & 0xff
    b3 = (i >>  8) & 0xff
    b4 = (i >> 4) & 0xff

    i += 1

2: 使用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 和私有 ip 有效,所以这些不是我目前想要的解决方案。

【问题讨论】:

  • 两种解决方案大致相同。您可能需要更好地解释要过滤掉的地址。
  • 如果你真的很严格,那是不可能完成的任务。例如。 X.Y.Z.127 是前缀为 /25 的网络中的广播地址,但如果前缀是通常的 /24,则它是主机地址。
  • 没有模式或简单的规则,你必须过滤掉所有这些:en.wikipedia.org/wiki/Reserved_IP_addresses
  • @FrankYellin 基本上,任何不是公共地址的东西。
  • @VPfB 我找到了这个链接,它显示了所有公共 ip 范围:public 我可以将它与an ip range generator 之类的东西一起使用吗?

标签: python


【解决方案1】:

您可以使用 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 here

【讨论】:

    【解决方案2】:

    我会修改 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-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2016-08-16
      • 2011-11-28
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多