Vipul
Vipul

Reputation: 125

Verifying IP address using regex in Python

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.

Upvotes: 0

Views: 185

Answers (4)

ajay_t
ajay_t

Reputation: 2385

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.

Upvotes: 2

Jims
Jims

Reputation: 1

You should remove the optionnal quantifier ? in :1?. Otherwise .... is a valid ip address.

Upvotes: 0

iced
iced

Reputation: 1582

len(ip.split(".")) == 4 and all(map(lambda o: o.isdigit() and int(o) <= 255, ip.split(".")))

Never ever use regexps in code. Please.

Upvotes: 0

Vipul
Vipul

Reputation: 125

I was making a mistake by not giving \ before . which was resulting in it matching any character.

import re

ip = '255.25.2.256'

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"

Upvotes: 0

Related Questions