ip address validation in python using regex

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip=241.1.1.112343434 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File <stdin>, line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

Use anchors instead:

aa=re.match(r^d{1,3}.d{1,3}.d{1,3}.d{1,3}$,ip)

These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you dont need the starting ^ anchor because its implicit in the .match() method).

Then, check if the regex did in fact match before trying to access its results:

if aa:
    ip = aa.group()

Of course, this is not a good approach for validating IP addresses (check out gnibblers answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:

ip_candidates = re.findall(rbd{1,3}.d{1,3}.d{1,3}.d{1,3}b, ip)

Here, the b word boundary anchors make sure that the digits dont exceed 3 for each segment.

ip address validation in python using regex

d{1,3} will match numbers like 00 or 333 as well which wouldnt be a valid ID.

This is an excellent answer from smink, citing:

ValidIpAddressRegex = ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$;

Leave a Reply

Your email address will not be published. Required fields are marked *