[Tutor] Validating String contains IP address

Martin A. Brown martin at linux-ip.net
Fri Mar 31 20:04:49 EDT 2017

Hello there,

>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 [0] approach for this sort of 

There are slight differences between the python2 third-party module 
ipaddr [1] and the python3 standard ipaddress module [2].  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 [3] 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
  import sys
      from ipaddress import ip_address as ipo
  except ImportError:
      from ipaddr import IPAddress as ipo
  for arg in sys.argv[1:]:
          print("%s is an IP." % (arg,))
      except ValueError:
          print("%s is not an IP." % (arg,))

When I save and run this (works the same in Python2 or Python3):

  $ python isarganip.py 192.v.12.7 text fe80::a64e:31ff:fe94:a160 is an IP. 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. is an IP. is an IP.

Basically, I'm lazy.  I let somebody else do the hard work of validation!

Good luck and happy IParsing!


 [0] http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-try-except-example
 [1] https://pypi.python.org/pypi/ipaddr
 [2] https://docs.python.org/3/library/ipaddress.html
 [3] https://docs.python.org/2/library/socket.html

Martin A. Brown

More information about the Tutor mailing list