Re: Control if a input text is IP

Discussion in 'Python' started by Fredrik Lundh, Feb 2, 2006.

  1. 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:

    def ipcheck(s):
    try:
    a, b, c, d = [chr(int(c)) for c in s.split(".")]
    except ValueError:
    return False
    else:
    return True

    another way is to use regular expressions; see

    http://www.regular-expressions.info/examples.html

    </F>
     
    Fredrik Lundh, Feb 2, 2006
    #1
    1. Advertising

  2. Fredrik Lundh

    Fuzzyman Guest

    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
     
    Fuzzyman, Feb 3, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guy
    Replies:
    5
    Views:
    2,832
    brucie
    Dec 13, 2003
  2. Romeyer Olivier
    Replies:
    12
    Views:
    11,021
  3. cjl
    Replies:
    1
    Views:
    10,503
    Michael Winter
    Oct 31, 2005
  4. Walter
    Replies:
    6
    Views:
    242
    Bob Barrows [MVP]
    Sep 17, 2004
  5. cjl
    Replies:
    7
    Views:
    185
    Thomas 'PointedEars' Lahn
    Oct 30, 2005
Loading...

Share This Page