[Tutor] Validating String contains IP address
Martin A. Brown
martin at linux-ip.net
Fri Mar 31 20:04:49 EDT 2017
>What's the best way to validate a string contains a IP address
If you are only talking about validating that something is an IP
address, then I can even give you a little Python2 / Python3 snippet
that can do that. I like the EAFP  approach for this sort of
There are slight differences between the python2 third-party module
ipaddr  and the python3 standard ipaddress module . The
latter is (I think) name-changed from the former, although I'm not
utterly sure of the history here. These two modules both parse IPs
(and have tools to allow you to parse IPv6 and IPv4 IPs and
So, rather than try to build your own, why not grab something
convenient from the (batteries-included) shelf?
Note, if you actually want to do something with the IP address
(convert to use for socket operations, store in a binary format
somewhere, use in network bitmath operations), then you'll want to
study these libraries and possibly also the socket  library.
But, if all you want to know is whether somebody provided a string
that is a valid IP (whether network address, host address or
broadcast address), you can use this little snippet:
from __future__ import print_function
from ipaddress import ip_address as ipo
from ipaddr import IPAddress as ipo
for arg in sys.argv[1:]:
print("%s is an IP." % (arg,))
print("%s is not an IP." % (arg,))
When I save and run this (works the same in Python2 or Python3):
$ python isarganip.py 192.168.7.0 192.168.7.256 192.v.12.7 text fe80::a64e:31ff:fe94:a160 255.255.255.255 0.0.0.0
192.168.7.0 is an IP.
192.168.7.256 is not an IP.
192.v.12.7 is not an IP.
text is not an IP.
fe80::a64e:31ff:fe94:a160 is an IP.
255.255.255.255 is an IP.
0.0.0.0 is an IP.
Basically, I'm lazy. I let somebody else do the hard work of validation!
Good luck and happy IParsing!
Martin A. Brown
More information about the Tutor