Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: '10.0.0.0/24' does not appear to be an IPv4 or IPv6 network

I want to work with IP subnets / IP addresses in Python. I created the Python code using the ipaddress module. When I run the code in the pycharm IDE, it works fine. But when I run on the command prompt by typing python test.py, it shows the following error.

ValueError: '10.0.0.0/24' does not appear to be an IPv4 or IPv6 network

test.py:

import ipaddress
srcIp = ipaddress.ip_network("10.0.0.0/24")
print(srcIp)
like image 438
Vishlesh Patel Avatar asked May 22 '15 05:05

Vishlesh Patel


2 Answers

It seems to work in Python 2.7, if you use a Unicode string.

import ipaddress
srcIp = ipaddress.ip_network(u'10.0.0.0/24')
print srcIp
like image 116
CubeRZ Avatar answered Nov 15 '22 21:11

CubeRZ


The underlying problem is that ip_network() instantiates a IPv4Network/IPv6Network object which requires the network address to be a unicode string. In Python 3 this is fine, but in Python 2 strings are not unicode by default. In Python 2:

>>> import ipaddress
>>> ipaddress.IPv4Network('10.0.0.0/24')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ipaddress.py", line 1486, in __init__
    self.network_address = IPv4Address(address)
  File "ipaddress.py", line 1271, in __init__
    self._check_packed_address(address, 4)
  File "ipaddress.py", line 528, in _check_packed_address
    expected_len, self._version))
ipaddress.AddressValueError: '10.0.0.0/24' (len 11 != 4) is not permitted as an IPv4 address (did you pass in a bytes instead of a unicode object?)
>>> ipaddress.IPv4Network(u'10.0.0.0/24')
IPv4Network(u'10.0.0.0/24')

ipaddress.ip_network() catches this exception and raises a ValueError with a less detailed message:

>>> ipaddress.ip_network('10.0.0.0/24')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ipaddress.py", line 148, in ip_network
    address)
ValueError: '10.0.0.0/24' does not appear to be an IPv4 or IPv6 network

So it looks like a unicode issue. One possible explanation is that maybe PyCharm is using Python >= 3.3 which provides module ipaddress in the standard library and in which strings are unicode by default. Your command line Python could be version 2, in which strings default to byte strings, and ipaddress.ip_network() will fail as shown above. I'm not sure about this because the print srcIp statement indicates that you are using Python 2 in both cases?

Another possibility is that PyCharm is somehow affecting the encoding of string literals within Python 2. I know almost nothing about PyCharm, but there are encoding options that can be set. Perhaps these effectively do something similar to from __future__ import unicode_literals.

like image 32
mhawke Avatar answered Nov 15 '22 20:11

mhawke