Verifying IP address using regex in Python
Question: I am trying to validate an IP address. Following is the code. Can anyone
please tell me what is wrong in the code?

    
    
    import re
    
    ip = '355.4'
    
    m = re.match('^((?:1?\d{0,2}|2[0-4]\d{1}|25[0-5]).){3}(?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])$', ip)
    if m:
        print "correct"
        print m.groups()
    else:
        print "wrong"
    

According to the IP given, it should print `wrong` as output but it prints
`correct ('4',)` as the output.


Answer: If you are allowed to `not to use regex`, you can use python's socket package
. `inet_aton("string")` converts the `string` to `ip` address,if this is not
valid ip then it will throw exception.

Simple example I have tried:

    
    
        import socket
    
        def check_valid(address):
            try:
                socket.inet_aton(address)
                return address.count('.') == 3
            except socket.error:
                return False
    
        if __name__ == "__main__":
            print check_valid("192.168.1.255")
    

It will check all valid ip address like `192.168.1.257` is invalid while
`192.168.1.255` is valid.

