phihag / ipaddress

Python 3.3+'s ipaddress for older Python versions
Other
105 stars 53 forks source link

Passing IPAddress objects to constructor again doesn't work #27

Closed hasegeli closed 8 years ago

hasegeli commented 8 years ago
Python 3.5.2 (default, Sep 26 2016, 21:36:20)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from ipaddress import ip_address
>>> ip_address(ip_address('1.1.1.1'))
IPv4Address('1.1.1.1')
Python 2.7.12 (default, Aug  4 2016, 10:57:00)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from ipaddress import ip_address
>>> ip_address(ip_address('1.1.1.1'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/pkg/lib/python2.7/site-packages/ipaddress.py", line 163, in ip_address
    ' a unicode object?' % address)
ipaddress.AddressValueError: '1.1.1.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?
phihag commented 8 years ago

Thank you for the report. The failing code is the inner ip_address('1.1.1.1') - the problem is unrelated to the outer construction. The code fails because by default '1.1.1.1' is a bytes object in Python 2. The bytes representation of ip_addresses is packed, andb'1.1.1.1'` is not a valid packed representation (luckily, or you'd get something completely different).

Either add from __future__ import unicode_literals to your code (that is the default and only behavior in Python 3), or add a u before the string literal, as in ip_address(u'1.1.1.1').