Last modified: Apr 27, 2025 By Alexander Williams

Validate IPv4 and IPv6 Addresses in Python

Validating IP addresses is a common task in networking. Python's ipaddress module makes it easy. This guide shows how to validate IPv4 and IPv6 addresses.

What is the ipaddress Module?

The ipaddress module is part of Python's standard library. It provides tools to create, manipulate, and validate IP addresses. No extra installation is needed.

How to Validate IPv4 Addresses

IPv4 addresses consist of four numbers separated by dots. Each number ranges from 0 to 255. Here's how to validate them:


import ipaddress

def validate_ipv4(ip_str):
    try:
        ipaddress.IPv4Address(ip_str)
        return True
    except ipaddress.AddressValueError:
        return False

# Test cases
print(validate_ipv4("192.168.1.1"))  # Valid
print(validate_ipv4("256.0.0.1"))    # Invalid


True
False

The IPv4Address constructor raises an exception for invalid addresses. The function catches it and returns False.

How to Validate IPv6 Addresses

IPv6 addresses are longer and use hexadecimal. They have eight groups separated by colons. Here's the validation code:


def validate_ipv6(ip_str):
    try:
        ipaddress.IPv6Address(ip_str)
        return True
    except ipaddress.AddressValueError:
        return False

# Test cases
print(validate_ipv6("2001:0db8:85a3::8a2e:0370:7334"))  # Valid
print(validate_ipv6("2001::25de::cade"))                # Invalid


True
False

The IPv6Address works like IPv4Address. It checks the address format and range.

Handling Both IPv4 and IPv6

Sometimes you need to validate both types. This function checks an address and returns its version:


def validate_ip(ip_str):
    try:
        ip_obj = ipaddress.ip_address(ip_str)
        return ip_obj.version  # Returns 4 or 6
    except ValueError:
        return 0  # Invalid

# Test cases
print(validate_ip("10.0.0.1"))                  # IPv4
print(validate_ip("2001:db8::1"))               # IPv6
print(validate_ip("invalid"))                   # Invalid


4
6
0

The ip_address function detects the IP version automatically. It returns 4, 6, or 0 for invalid addresses.

Common Errors and Fixes

Working with IP addresses can raise exceptions. Here are some common issues:

1. Incorrect Format: Ensure the address follows the correct structure. IPv4 uses dots, IPv6 uses colons.

2. Out of Range Values: Each part of an IPv4 must be between 0 and 255. IPv6 uses hexadecimal (0-FFFF).

If you face TypeError issues, check our guide on Fix TypeError: 'builtin_function_or_method' Not Subscriptable.

Practical Use Cases

IP validation is useful in many scenarios:

1. Network Configuration: Validate user input for server setups.

2. Security Checks: Filter valid IPs in firewall rules.

3. Data Cleaning: Check IP addresses in logs or databases.

For more Python networking, see Python pyzmq.zmq_recv_multipart() Guide.

Conclusion

The ipaddress module simplifies IP validation in Python. It handles both IPv4 and IPv6 with minimal code. Always validate IPs before processing them.

For more Python tips, check our guide on How to Install IPython in Python Step by Step.