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

六月ゝ 毕业季﹏ 提交于 2020-05-15 03:38:39

问题


I am trying to list valid hosts for given network range via Python3, ipaddress module but I am getting ValueError ValueError('%s has host bits set' % self) while trying to list all valid hosts.

>>> 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

回答1:


As stated in documentation:

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

The number after slash(16 in your case) means, number of bits reserved for subnet, so last 16 bits are your host bits. This method requires those bits as 0 (unset).




回答2:


You have another option. From the document mentioned above, we can see that:

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.

So, please try following again.

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


来源:https://stackoverflow.com/questions/40839147/ipaddress-module-valueerrors-has-host-bits-set-self

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!