How to validate IP address in Python?

krupan picture krupan · Nov 26, 2008 · Viewed 250.4k times · Source

What's the best way to validate that an IP entered by the user is valid? It comes in as a string.

Answer

Dustin picture Dustin · Nov 26, 2008

Don't parse it. Just ask.

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal