How to fix Python ipaddress.IPv6Network ValueError: ... has host bits set

Problem:

When trying to parse an IPv6 network address in Python using code like

import ipaddress
ipaddress.IPv6Network("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64")

you see an error message like

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_154945/1312927855.py in <module>
      1 import ipaddress
----> 2 ipaddress.IPv6Network("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64")

/usr/lib/python3.8/ipaddress.py in __init__(self, address, strict)
   2106         if packed & int(self.netmask) != packed:
   2107             if strict:
-> 2108                 raise ValueError('%s has host bits set' % self)
   2109             else:
   2110                 self.network_address = IPv6Address(packed &

ValueError: 2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64 has host bits set

Solution 1: Maybe you should use IPv6Address instead of IPv6Network

If you intend to parse the address and don’t care about the network, use ipaddress.IPv6Address but remember that the CIDR mask (e.g. /64)  needs to be removed. If you want to use IPv6Address or IPv6Network really depends on what you want to do with it - if you want to refer to a specific host, you almost always want to use IPv6Address.

import ipaddress
ipaddress.IPv6Address("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69")

Solution 2: Use strict=False to let IPv6Network discard the host bits:

strict=False basically ignores this error

import ipaddress
ipaddress.IPv6Network("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64", strict=False)

Note that the result will be

IPv6Network('2a01:c23:c0bb:d00::/64')

so the information in the host bits will be lost!

Solution 2: Remove the host bits manually

Since the host bits will be discarded anyway, you can just specify the IPv6 network with the correct netmask:

import ipaddress
ipaddress.IPv6Network("2a01:c23:c0bb:d00::/64")