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)
It seems to work in Python 2.7, if you use a Unicode string.
The underlying problem is that
ip_network()
instantiates aIPv4Network/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:ipaddress.ip_network()
catches this exception and raises aValueError
with a less detailed message: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, andipaddress.ip_network()
will fail as shown above. I'm not sure about this because theprint 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
.Just noting that 10.0.0.0/24 is an invalid subnet. The first valid subnet within the 10.0.0.0/8 (Class A) network, now sliced with a
/24
subnet mask is...10.0.1.0/24
. You have to throw away the top/bottom on the network side just like you do for the top/bottom for the host side of that bitmask. For the same reason, 10.255.255.0/24 is also invalid.For any given subnet mask there are 2x - 2 subnets and 2x - 2 hosts
...where x is the number of bits on that side of the mask. So for
/24
that's 24 on the network side and 8 on the host side making 16777214 subnets and 254 hosts. Note the "- 2" part of that calculation on the network side of the bitmask. That means that you have to throw away (you can't issue) those since they mean something to the transport layer of tcp/ip, in this case.This should make sense to anyone who already knows that you similarly can't bind any
10.x.y.0/24
and10.x.y.255/24
addresses since they already mean something.