[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 
thing.

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 
prefixes).

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
  
  try:
      from ipaddress import ip_address as ipo
  except ImportError:
      from ipaddr import IPAddress as ipo
  
  for arg in sys.argv[1:]:
      try:
          ipo(arg)
          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.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

 [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
     https://docs.python.org/3/library/socket.html

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list