0
0
PythonHow-ToBeginner · 3 min read

How to Validate IP Address in Python Easily

You can validate an IP address in Python using the ipaddress module by trying to create an IPv4Address or IPv6Address object. If it raises a ValueError, the IP address is invalid.
📐

Syntax

Use the ipaddress module's classes to validate IP addresses. The main classes are IPv4Address for IPv4 and IPv6Address for IPv6.

Try to create an instance with the IP string. If it succeeds, the IP is valid. If it raises ValueError, the IP is invalid.

python
import ipaddress

# Validate IPv4
ip = ipaddress.IPv4Address('192.168.1.1')

# Validate IPv6
ip6 = ipaddress.IPv6Address('2001:0db8::1')
💻

Example

This example shows how to check if a string is a valid IPv4 or IPv6 address using ipaddress. It prints whether the IP is valid or not.

python
import ipaddress

def validate_ip(ip_str):
    try:
        ipaddress.ip_address(ip_str)
        print(f"'{ip_str}' is a valid IP address.")
    except ValueError:
        print(f"'{ip_str}' is NOT a valid IP address.")

# Test examples
validate_ip('192.168.1.1')
validate_ip('256.100.50.0')
validate_ip('2001:0db8::1')
validate_ip('1234::5678::9')
Output
'192.168.1.1' is a valid IP address. '256.100.50.0' is NOT a valid IP address. '2001:0db8::1' is a valid IP address. '1234::5678::9' is NOT a valid IP address.
⚠️

Common Pitfalls

Common mistakes include:

  • Trying to validate IPs with regex, which is error-prone and complex.
  • Not handling exceptions when the IP is invalid.
  • Confusing IPv4 and IPv6 formats.

Always use ipaddress.ip_address() for simplicity and reliability.

python
import ipaddress

# Wrong way: using regex (not recommended)
import re
pattern = r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"

ip = '256.100.50.0'
if re.match(pattern, ip):
    print(f"'{ip}' looks like an IPv4 address but may be invalid.")
else:
    print(f"'{ip}' is not a valid IPv4 format.")

# Right way: using ipaddress
try:
    ipaddress.IPv4Address(ip)
    print(f"'{ip}' is a valid IPv4 address.")
except ValueError:
    print(f"'{ip}' is NOT a valid IPv4 address.")
Output
'256.100.50.0' looks like an IPv4 address but may be invalid. '256.100.50.0' is NOT a valid IPv4 address.
📊

Quick Reference

Summary tips for IP validation in Python:

  • Use ipaddress.ip_address(ip_string) to validate both IPv4 and IPv6.
  • Catch ValueError to detect invalid IPs.
  • Do not rely on regex for IP validation.
  • Use IPv4Address or IPv6Address if you want to validate specific IP versions.

Key Takeaways

Use the built-in ipaddress module to validate IP addresses safely and easily.
Wrap IP parsing in try-except to catch invalid IPs via ValueError.
Avoid regex for IP validation because it is complicated and error-prone.
ipaddress.ip_address() works for both IPv4 and IPv6 addresses.
Use IPv4Address or IPv6Address classes to validate specific IP versions.