validation – How to validate IP address in Python?

validation – How to validate IP address in Python?

Dont parse it. Just ask.

import socket

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

From Python 3.4 on, the best way to check if an IPv6 or IPv4 address is correct, is to use the Python Standard Library module ipaddress – IPv4/IPv6 manipulation library s.a. https://docs.python.org/3/library/ipaddress.html for complete documentation.

Example :

#!/usr/bin/env python

import ipaddress
import sys

try:
    ip = ipaddress.ip_address(sys.argv[1])
    print(%s is a correct IP%s address. % (ip, ip.version))
except ValueError:
    print(address/netmask is invalid: %s % sys.argv[1])
except:
    print(Usage : %s  ip % sys.argv[0])

For other versions: Github, phihag / Philipp Hagemeister,Python 3.3s ipaddress for older Python versions, https://github.com/phihag/ipaddress

The backport from phihag is available e.g. in Anaconda Python 2.7 & is included in Installer. s.a. https://docs.continuum.io/anaconda/pkg-docs

To install with pip:

pip install ipaddress

s.a.: ipaddress 1.0.17, IPv4/IPv6 manipulation library, Port of the 3.3+ ipaddress module, https://pypi.python.org/pypi/ipaddress/1.0.17

validation – How to validate IP address in Python?

import socket

def is_valid_ipv4_address(address):
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:  # no inet_pton here, sorry
        try:
            socket.inet_aton(address)
        except socket.error:
            return False
        return address.count(.) == 3
    except socket.error:  # not a valid address
        return False

    return True

def is_valid_ipv6_address(address):
    try:
        socket.inet_pton(socket.AF_INET6, address)
    except socket.error:  # not a valid address
        return False
    return True

Leave a Reply

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