A python function to capture an IP address or range

I recently 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 lenght’s. If it doesn’t already do it like that when checking int’s 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 <= int(mask) <= 32):
            return False
    else:
        ip = address

    for octet in ip.split('.'):
        if not (0 <= int(octet) <= 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 here them so please drop me a line.

GrtzG

Dit bericht is geplaatst in All ENGLISH articles, Technical met de tags , , , , , . Bookmark de permalink.

Geef een reactie

Je e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *

*

* Copy this password:

* Type or paste password here:

7,573 Spam Comments Blocked so far by Spam Free Wordpress

De volgende HTML tags en attributen zijn toegestaan: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>