Skip to content
Python Basics: Validating IP Addresses and Subnets with ipaddress

Python Basics: Validating IP Addresses and Subnets with ipaddress

October 12, 2026

Python’s standard-library ipaddress module turns address text into objects you can validate, compare, and check against a subnet.

Use Python 3.12 or newer in Bash on Linux. Each example runs independently with documentation addresses. Nothing connects to a network or changes your computer’s settings.

Validate IPv4 and IPv6 text

Save as demo_ipaddress_1.py:

from ipaddress import ip_address

for text in ("192.0.2.7", "2001:0db8::7", "999.0.2.7"):
    try:
        address = ip_address(text)
    except ValueError:
        print(f"{text}: invalid")
    else:
        print(f"{text}: IPv{address.version}, normalized={address}")

Run it from the directory where you saved it:

python3 demo_ipaddress_1.py

Output:

192.0.2.7: IPv4, normalized=192.0.2.7
2001:0db8::7: IPv6, normalized=2001:db8::7
999.0.2.7: invalid

ip_address() detects the address family and rejects invalid text with ValueError. The IPv6 string representation uses compressed notation. IPv4 parts must be between 0 and 255; leading zeroes are rejected. Valid syntax does not prove an address is reachable or trusted.

Test subnet membership

Save as demo_ipaddress_2.py:

from ipaddress import ip_address, ip_network

network = ip_network("192.0.2.0/24")
print("Addresses:", network.num_addresses)
for text in ("192.0.2.7", "192.0.3.7", "192.0.2.255"):
    print(f"{text}: {ip_address(text) in network}")

Run it from the directory where you saved it:

python3 demo_ipaddress_2.py

Output:

Addresses: 256
192.0.2.7: True
192.0.3.7: False
192.0.2.255: True

The /24 prefix fixes the first 24 bits of this IPv4 network. Membership checks the whole range, including its network and broadcast addresses. It does not tell you whether an address is assignable to a host. Use address objects with in, rather than raw strings.

Separate a host address from its network

Save as demo_ipaddress_3.py:

from ipaddress import ip_interface, ip_network

text = "192.0.2.7/24"
try:
    ip_network(text)
except ValueError:
    print("Strict network parsing rejected host bits")
print("Containing network:", ip_network(text, strict=False))
interface = ip_interface(text)
print("Host:", interface.ip)
print("Network:", interface.network)

Run it from the directory where you saved it:

python3 demo_ipaddress_3.py

Output:

Strict network parsing rejected host bits
Containing network: 192.0.2.0/24
Host: 192.0.2.7
Network: 192.0.2.0/24

By default, ip_network() requires a network boundary. Use strict=False deliberately when you want the containing network: it discards the host bits. Use ip_interface() when you need to preserve both the host address and its prefix.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on