Control if a input text is IP

Fuzzyman fuzzyman at gmail.com
Fri Feb 3 08:09:21 EST 2006


Fredrik Lundh wrote:
> Sbaush wrote:
>
> > My app has in input an ip address in IPv4 notation.
> > is there a function that control if input is a string in IPv4 notation?
>
> here's one way to do it:

Here's a function from the 'validate' module that comes with ConfigObj
:

def dottedQuadToNum(ip):
    """
    Convert decimal dotted quad string to long integer

    >>> dottedQuadToNum('1 ')
    1L
    >>> dottedQuadToNum(' 1.2')
    16777218L
    >>> dottedQuadToNum(' 1.2.3 ')
    16908291L
    >>> dottedQuadToNum('1.2.3.4')
    16909060L
    >>> dottedQuadToNum('1.2.3. 4')
    Traceback (most recent call last):
    ValueError: Not a good dotted-quad IP: 1.2.3. 4
    >>> dottedQuadToNum('255.255.255.255')
    4294967295L
    >>> dottedQuadToNum('255.255.255.256')
    Traceback (most recent call last):
    ValueError: Not a good dotted-quad IP: 255.255.255.256
    """

    # import here to avoid it when ip_addr values are not used
    import socket, struct

    try:
        return struct.unpack('!L',
            socket.inet_aton(ip.strip()))[0]
    except socket.error:
        # bug in inet_aton, corrected in Python 2.3
        if ip.strip() == '255.255.255.255':
            return 0xFFFFFFFFL
        else:
            raise ValueError('Not a good dotted-quad IP: %s' % ip)
    return

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml




More information about the Python-list mailing list