In this article, we can learn how to validate IP addresses in Python. We will see two ways to validate IP address with Python:

(1) using socket library

import socket

def is_valid_ip(ip_address):
	try:
    	socket.inet_aton(ip_address)
    	return True
	except socket.error:
    	return False

print(is_valid_ip("192.168.0.0")) # True
print(is_valid_ip("192.256.0.1")) # False

(2) using regex

import re

regex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
re.match(regex,"192.168.0.0").group()

(2) custom validation function

def validate_ip(ip):
	try:
    	parts = ip.split('.')
    	return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
	except ValueError:
    	return False
	except (AttributeError, TypeError):
    	return False
    
validate_ip("192.256.0.0")

If you need to validate IP addresses with Pandas please check: How to validate IP address in Pandas

Validate IP with socket

To validate an IP address in Python, we can use the socket library to attempt to connect to the address.

If the connection is successful, the address is considered valid:

import socket

def is_valid_ip(ip_address):
	try:
    	socket.inet_aton(ip_address)
    	return True
	except socket.error:
    	return False

print(is_valid_ip("192.168.0.0")) # True
print(is_valid_ip("192.256.0.1")) # False

Validate IP with regex

As faster alternative we can define regular expressions like:

  • strict - "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
  • loose - r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"

In order to validate if a give IP address is valid or not:

import re

regex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
re.match(regex,"192.168.0.0").group()

This will validate successfully 192.168.0.0:

'192.168.0.0'

While address re.match(regex,"192.256.0.0") will fail.

Custom validation of IP addresses

Finally if we need a custom validation for IP addresses in Python. For example, the validation of range of IP addresses or other limitations.

Than we can define function and tune it for a more precise results:

def validate_ip(ip):
	try:
    	parts = ip.split('.')
    	return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
	except ValueError:
    	return False
	except (AttributeError, TypeError):
    	return False
    
validate_ip("192.256.0.0")

This will return False.

While validating the validate_ip("192.255.0.0") will result in True.