如何修复 python ipaddress.IPv6Address AddressValueError: Unexpected '/' in '.../64'
问题:
尝试在 Python 中使用类似这样的代码解析 IPv6 网络地址时
example_ipaddress.py
import ipaddress
ipaddress.IPv6Network("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64")你看到类似这样的错误消息
AddressValueError Traceback (most recent call last)
/tmp/ipykernel_154945/2602627019.py in
/usr/lib/python3.8/ipaddress.py in init(self, address) 1836 addr_str = str(address) 1837 if ‘/’ in addr_str: 1839 self._ip = self._ip_int_from_string(addr_str) 1840
AddressValueError: Unexpected ‘/’ in ‘2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64’
traceback.txt
---------------------------------------------------------------------------
AddressValueError Traceback (most recent call last)
/tmp/ipykernel_154945/2602627019.py in <module>
----> 1 ipaddress.IPv6Address("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64")
/usr/lib/python3.8/ipaddress.py in __init__(self, address)
1836 addr_str = str(address)
1837 if '/' in addr_str:
-> 1838 raise AddressValueError("Unexpected '/' in %r" % address)
1839 self._ip = self._ip_int_from_string(addr_str)
1840
AddressValueError: Unexpected '/' in '2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64'解决方案 1:删除 CIDR 网络掩码(/64)
只需删除斜杠及其后面的部分(CIDR 网络掩码)。
解决方案 2:也许你应该使用 IPv6Network 而不是 IPv6Address
如果你打算解析网络,使用 ipaddress.IPv6Network,但记住这将丢弃所有主机位。你想使用 IPv6Address 还是 IPv6Network 确实取决于你想用它做什么 - 如果你想引用特定主机,你几乎总是想使用 IPv6Address。
example_ipv6network.py
import ipaddress
ipaddress.IPv6Network("2a01:c23:c0bb:d00:8ce6:2eff:fe60:cc69/64", strict=False)注意添加 strict=False 是为了防止由于设置了主机位而引发异常 - 参见如何修复 Python ipaddress.IPv6Network ValueError: … has host bits set
Check out similar posts by category:
Networking, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow