How to validate an IP address in python

01 Sep 2008

The function you want is socket.inet_aton. It returns a binary string on success or throws socket.error exception if invalid. Check out other conversion functions in the socket module

>>> from socket import inet_aton

>>> inet_aton("127.0.0.1")
'\x7f\x00\x00\x01'

# that good.
#  here's a bad example:

>>> inet_aton("127.0.0.12345")
Traceback (most recent call last):
  File "", line 1, in 
socket.error: illegal IP address string passed to inet_aton
>>> 

# tada!