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("")

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

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

# tada!