ipaddress 模块 ValueError('%s 设置了主机位' % self)

ipaddress module ValueError('%s has host bits set' % self)

我正在尝试通过 Python3、ipaddress 模块列出给定网络范围内的有效主机,但出现 ValueError ValueError('%s has host bits set' % self) 在尝试列出所有有效主机时。

>>> ip_range=input("Enter IP Range:")
Enter IP Range:192.168.56.101/16
>>> list(ipa.ip_network(ip_range).hosts())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/ipaddress.py", line 74, in ip_network
    return IPv4Network(address, strict)
  File "/usr/local/lib/python3.5/ipaddress.py", line 1536, in __init__
    raise ValueError('%s has host bits set' % self)
ValueError: 192.168.56.101/16 has host bits set

documentation所述:

A ValueError is raised if address does not represent a valid IPv4 or IPv6 address, or if the network has host bits set.

斜杠后的数字(在您的例子中为 16)表示为 subnet 保留的位数,因此最后 16 位是您的主机位。此方法要求这些位为 0(未设置)。

你还有另一个选择。 从上面提到的document可以看出:

If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.

所以,请重新尝试关注。

ip_range = '192.168.56.101/16'
list(ipaddress.ip_network(ip_range, False).hosts())

两种解决方案

要么更改输入,要么更改代码。

1:改变输入

上面你提到你的输入是 192.168.56.101/1616 定义此 ip 范围的主机位。 Python 希望您清除它们(将所有这些位设置为 0)。您将 ip 指定为 192.168.56.101,同时告知有 16 主机位。 Python 预计最后 16 位为 0

在二进制中,IP 如下所示:11000000.10101000.00111000.01100101您需要清除最后 16 位。 它看起来像这样:11000000.10101000.0.0(等于十进制的 192.168.0.0)。

结论: 您需要将输入更改为 192.168.0.0/16 才能正常工作。

2:更改代码

查看 Python Docs:

If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.

因此,通过更改代码停用 strict 模式:

ip_network(target) 更改为 ip_network(target, False)

这里你可以在技术上输入 192.168.56.101/16

参考资料


这个回答晚了,但我相信它很有帮助!