chowpay chowpay - 10 days ago 4
Python Question

ipaddress.py getting errors on a valid ip address

I'm running python 2.7. I downloaded the raw of ipaddress.py (https://github.com/phihag/ipaddress) . I tried to run a test to validate the ip address per the example. But even valid ip addresses seem to be invalid.

>>> 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?


What am I missing?
Thanks

Answer

From the docs:

Note that as in Python 3.3+ you must use character strings and not byte strings for textual IP address representations:

I double checked it, and using from __future__ import unicode_literals allows you to skip the u in u'make_me_unicode_string'.

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