文章内容

2022/2/24 16:41:44,作 者: 黄兵

ipaddress.AddressValueError: Expected 4 octets in '17619084'

最近在使用 Python ipaddress 包转换 IP 地址的时候出现了如下错误:

 File "/usr/lib/python3.8/ipaddress.py", line 1144, in _ip_int_from_string

    raise AddressValueError("Expected 4 octets in %r" % ip_str)

ipaddress.AddressValueError: Expected 4 octets in '17619084'

出现问题的原因:

1、数据类型错误;

2、IP 地址错误。

解决方案:

1、数据类型错误,下面是数据类型错误的一个示例:

str(IPv4Address(item.ip_from))

上面实例中 item.ip_form 的数据类型是 decimal 所以需要转换成 int 或 string 类型,代码如下:

str(IPv4Address(int(item.ip_from)))

2、IP 地址错误,如果是 IPv6 地址使用上面的代码会出现问题:

ipaddress.IPv4Address('2001:0db8:85a3:0000:0000:8a2e:0370:7334')

上面明显是一个 IPv6 地址,会出现错误,具体错误内容:

Traceback (most recent call last):
  File "input", line 1, in module
  File "/usr/lib/python3.5/ipaddress.py", line 1284, in __init__
    self._ip = self._ip_int_from_string(addr_str)
  File "/usr/lib/python3.5/ipaddress.py", line 1118, in _ip_int_from_string
    raise AddressValueError("Expected 4 octets in %r" % ip_str)
ipaddress.AddressValueError: Expected 4 octets in '2001:0db8:85a3:0000:0000:8a2e:0370:7334'


参考资料:

1、How can I validate a network route with Python


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - ipaddress.AddressValueError: Expected 4 octets in '17619084'

分享到:

发表评论

评论列表