Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ip address validation in python using regex [duplicate]

Tags:

In the following ip address validation i want to see if it a valid ip address or not how can i do this using the below re

>>> ip="241.1.1.112343434" 
>>> aa=re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^0-9]",ip)
>>> aa.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
like image 247
Rajeev Avatar asked Apr 10 '12 09:04

Rajeev


People also ask

How do you represent an IP address in regex?

\d{1,3}\b will match any IP address just fine. But will also match 999.999. 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.

How do you check if a string is a valid IP address Python?

The simplest way to validate if a string represents an IP address is by using the Python ipaddress module. Let's open the Python shell and see what the ipaddress. ip_address() function returns when we pass to it strings that represent a valid and an invalid IPv4 address.

Which of the following regex matches is a valid IP?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."


1 Answers

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
like image 169
John La Rooy Avatar answered Oct 01 '22 12:10

John La Rooy