Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a RegEx to match IP addresses

Tags:

I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...

As a simple test, I have the following...

import re  pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}") test = pat.match(hostIP) if test:    print "Acceptable ip address" else:    print "Unacceptable ip address" 

However when I pass random values into it, it returns "Acceptable IP address" in most cases, except when I have an "address" that is basically equivalent to \d+.

like image 460
MHibbin Avatar asked Jun 29 '12 14:06

MHibbin


1 Answers

Using regex to validate IP address is a bad idea - this will pass 999.999.999.999 as valid. Try this approach using socket instead - much better validation and just as easy, if not easier to do.

import socket  def valid_ip(address):     try:          socket.inet_aton(address)         return True     except:         return False  print valid_ip('10.10.20.30') print valid_ip('999.10.20.30') print valid_ip('gibberish') 

If you really want to use parse-the-host approach instead, this code will do it exactly:

def valid_ip(address):     try:         host_bytes = address.split('.')         valid = [int(b) for b in host_bytes]         valid = [b for b in valid if b >= 0 and b<=255]         return len(host_bytes) == 4 and len(valid) == 4     except:         return False 
like image 111
Maria Zverina Avatar answered Oct 01 '22 09:10

Maria Zverina