How to Validate an IP Address in Python

Validating data is one of the many tasks engineers face around the world. Your users make typos as often as anyone else, so you must try to catch those errors.

One common type of information that an engineer will need to capture is someone who wants to edit or enter an IP address for a device. These addresses are made up of four sets of numbers separated by periods. Each of these four sets are made up of integers from 0-255.

The lowest IP address would be 0.0.0.0, and the highest would be 255.255.255.255.

In this article, you will look at the following ways to validate an IP address with Python:

  • Using the socket module
  • Using the ipaddress module

Let’s get started!

Using the socket Module

Python has lots of modules or libraries built-in to the language. One of those modules is the socket module.

Here is how you can validate an IP address using the socket module:

import socket

try:
    socket.inet_aton(ip_address)
    print(f"{ip_address is valid")
except socket.error:
    print(f"{ip_address} is not valid!")

Unfortunately, this doesn’t work with all valid IP addresses. For example, this code won’t work IPv6 variants, only IPv4. You can use socket.inet_pton(socket_family, address)  and specify which IP version you want to use, which may work. However, the inet_pton() function is only available on Unix.

Luckily, there is a better way!

Using the ipaddress Module

Python also includes the ipaddress module in its standard library. This module is available for use on all platforms and can be used to validate IPv4 and IPv6.

Here is how you can validate an IP address using Python’s built-in ipaddress module:

import ipaddress

def ip_address_validator(ip):
    try:
        ip_obj = ipaddress.ip_address(ip)
        print(f"{ip} is a valid IP address")
    except ValueError:
        print(f"ERROR: {ip} is not a valid IP address!")
        
ip_address_validator("192.168.5.1")

The ipaddress module makes validating IP addresses even simpler than the socket module!

Wrapping Up

The Python programming language provides a couple of modules that you can use to validate IP addresses. You can use either the socket module or the ipaddress module. The socket module has some limitations on platforms other than Unix. That makes using the ipaddress module preferable since you may use it on any platform.

Note: You could probably find a regular expression that you could use to validate an IP address, too. However, leveraging the ipaddress module is simpler and easier to debug.