Raja Raja - 7 days ago 8
Python Question

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

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

Answer

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

Comments