I needed a function that validates an IP address or network range. Since my python application will pass it as a parameter to iptables it needs to be correct and not ‘close to’. So I dug in …

Validating an IP address or range with just a regex seems like self castigation. I looked at the source code of iptables and it check’s whether or not 1 octet fits in a byte. With your octet being only valid from 0 up to and 255 it must fit in 1 byte. That method seems ok but when you’re writing interpretable code the interpreter most likely does a better job then you in checking byte length’s. And I assume it already checks it like this:

if not (0 <= int(octet) <= 255):

Digesting all that information I wrote the function below that takes an IP address or range and simply returns ‘True’ or ‘False’.

def check_address(address):

    if not (re.search('^d{1,3}.d{1,3}.d{1,3}.d{1,3}(|/d{1,2})$', address)):
        return False

    if (address.count('/') == 1):
        (ip, mask) = address.split('/')
        if not (0 &lt;= int(mask) &lt;= 32):
            return False
        ip = address

    for octet in ip.split('.'):
        if not (0 &lt;= int(octet) &lt;= 255):
            return False

    return True

IMHO, it’s very safe and very readable. You know … KISS.

If you have suggestions on how to do this more pythonesque I’m very curious to hear them so please drop me a line.