Last modified: Sep 13, 2026

Check If IP Address Is Valid Python

Validating an IP address in Python is a common task. Developers often need to ensure user input or data matches a valid IP format before processing. This article explains how to check if an IP address is valid using Python.

We will cover both IPv4 and IPv6 validation. You will learn multiple methods including built-in libraries and custom logic.

What Is an IP Address

An IP address identifies a device on a network. There are two main types:

  • IPv4 – Four numbers separated by dots (e.g., 192.168.1.1)
  • IPv6 – Eight groups of hex digits separated by colons (e.g., 2001:0db8:85a3::8a2e:0370:7334)

Each part of an IPv4 address must be between 0 and 255. For IPv6, each group contains 1 to 4 hexadecimal digits.

Using the ipaddress Module

Python provides a built-in module called ipaddress. It offers functions to validate and manipulate IP addresses easily.

Use ipaddress.ip_address() to check validity. If the input is invalid, it raises a ValueError.


import ipaddress

# Valid IPv4
try:
    ip = ipaddress.ip_address("192.168.1.1")
    print(f"Valid IP: {ip}")
except ValueError:
    print("Invalid IP address")

# Invalid IPv4
try:
    ip = ipaddress.ip_address("999.168.1.1")
    print(f"Valid IP: {ip}")
except ValueError:
    print("Invalid IP address")

Valid IP: 192.168.1.1
Invalid IP address

This method works for both IPv4 and IPv6 addresses automatically.

Validating IPv4 with Custom Logic

Sometimes you may want to validate manually without using modules. Here is how to validate an IPv4 address using string methods.


def is_valid_ipv4(ip):
    # Split the IP into parts
    parts = ip.split(".")
    
    # Must have exactly 4 parts
    if len(parts) != 4:
        return False
    
    for part in parts:
        # Each part must be a digit and within range
        if not part.isdigit():
            return False
        num = int(part)
        if num < 0 or num > 255:
            return False
        # Avoid leading zeros like 01 or 001
        if len(part) > 1 and part[0] == "0":
            return False
    
    return True

# Test cases
print(is_valid_ipv4("192.168.1.1"))   # True
print(is_valid_ipv4("256.168.1.1"))   # False
print(is_valid_ipv4("192.168.1"))     # False
print(is_valid_ipv4("192.168.01.1"))  # False

True
False
False
False

This approach helps you understand the validation rules clearly.

Validating IPv6 with Custom Logic

IPv6 validation is more complex due to hexadecimal values and optional compression. Here is a simplified version.


def is_valid_ipv6(ip):
    # Split by colon
    parts = ip.split(":")
    
    # IPv6 must have 8 parts (or fewer with compression)
    if len(parts) > 8 or len(parts) < 3:
        return False
    
    for part in parts:
        # Empty part allowed only with double colon
        if part == "":
            continue
        # Check length and hex characters
        if len(part) > 4:
            return False
        try:
            int(part, 16)
        except ValueError:
            return False
    
    return True

# Test cases
print(is_valid_ipv6("2001:0db8:85a3::8a2e:0370:7334"))  # True
print(is_valid_ipv6("2001:0db8:85a3::8a2e:0370:7334:extra"))  # False
print(is_valid_ipv6("gggg::1"))  # False

True
False
False

Using Regular Expressions

Regular expressions offer another way to validate IP addresses. They are powerful but can be hard to read.


import re

# Regex pattern for IPv4
ipv4_pattern = r"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"

# Validate using regex
def validate_ipv4_regex(ip):
    return re.match(ipv4_pattern, ip) is not None

print(validate_ipv4_regex("192.168.1.1"))  # True
print(validate_ipv4_regex("256.168.1.1"))  # False

True
False

Regex is useful but not recommended for beginners due to complexity.

Choosing the Right Method

Here are guidelines to pick the best method:

  • Built-in ipaddress – Best for most cases
  • Custom logic – Good for learning or special rules
  • Regular expressions – Useful when integrating into larger regex patterns

For production code, always prefer the ipaddress module. It handles edge cases correctly.

Common Mistakes to Avoid

Avoid these mistakes when validating IP addresses:

  • Not handling leading zeros in IPv4
  • Allowing out-of-range octets
  • Ignoring IPv6 compression rules
  • Using regex without testing edge cases

Always test your validation function with multiple inputs.

Conclusion

Validating IP addresses in Python is straightforward. The ipaddress module is the most reliable method. Custom logic helps with understanding and special cases. Regular expressions work but require careful testing.

Choose the method that fits your needs. Always validate user input to prevent errors and security issues.

Start with the ipaddress module for clean and correct validation. Move to custom logic only when necessary.