Raja Raja - 1 month ago 12
Python Question

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

I am trying to list valid hosts for given network range via Python3,

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:
>>> 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: has host bits set


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