Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 346
chowpay Avatar asked Dec 06 '25 19:12

chowpay


2 Answers

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')
like image 116
paragbaxi Avatar answered Dec 08 '25 08:12

paragbaxi


You need to pass a unicode string. You can do it like this:

ipaddress.ip_address(u'192.168.0.1')

or

ipaddress.ip_address(unicode('192.168.0.1'))
like image 31
Fejs Avatar answered Dec 08 '25 08:12

Fejs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!