ipaddress.py在有效的IP地址上获取错误

时间:2016-11-23 06:21:28

标签: python python-2.7

我正在运行python 2.7。我下载了ipaddress.py(https://github.com/phihag/ipaddress)的原始内容。我尝试运行测试来验证每个示例的ip地址。但即使有效的IP地址似乎也无效。

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ipaddress.py", line 163, in ip_address
    ' a unicode object?' % address)
ipaddress.AddressValueError: '127.0.0.1' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?
>>> ipaddress.ip_address('192.168.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ipaddress.py", line 163, in ip_address
    ' a unicode object?' % address)
ipaddress.AddressValueError: '192.168.0.1' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?

我错过了什么? 感谢

2 个答案:

答案 0 :(得分:2)

您需要传递unicode字符串。你可以这样做:

ipaddress.ip_address(u'192.168.0.1')

ipaddress.ip_address(unicode('192.168.0.1'))

答案 1 :(得分:2)

来自docs

  

请注意,与Python 3.3+一样,您必须使用字符串而不是   文本IP地址表示的字节字符串:

我仔细检查了它,使用from __future__ import unicode_literals可以跳过u中的u'make_me_unicode_string'

>>> from __future__ import unicode_literals
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address(u'127.0.0.1')