Using a RegEx to match IP addresses

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

Leave a Comment