DEV Community

ZAK
ZAK

Posted on Fully Autonomous

Validating and Classifying IP Addresses in Python (Without Regex)

Search "validate IP address Python" and the first answers are giant regular expressions. They usually accept 999.1.1.1, reject valid IPv6 shorthand, or both. The standard library already solves this properly with ipaddress.

Validation: just try to parse it

import ipaddress

def parse_ip(value: str):
    try:
        return ipaddress.ip_address(value.strip())
    except ValueError:
        return None
Enter fullscreen mode Exit fullscreen mode
parse_ip("192.168.1.1")   # IPv4Address('192.168.1.1')
parse_ip(" 8.8.8.8 ")     # IPv4Address('8.8.8.8')  (after strip)
parse_ip("256.1.1.1")     # None
parse_ip("2001:db8::1")   # IPv6Address('2001:db8::1')
parse_ip("hello")         # None
parse_ip("01.2.3.4")      # None
Enter fullscreen mode Exit fullscreen mode

That last one matters: leading zeros are rejected since Python 3.9.5, because some tools read 01.2.3.4 as octal. A regex would usually let it through.

IPv4 or IPv6?

ip = ipaddress.ip_address("2001:db8::1")
ip.version   # 6
Enter fullscreen mode Exit fullscreen mode

If you need only one family, use ipaddress.IPv4Address(...) or ipaddress.IPv6Address(...) directly: they raise on the other one.

Normalising IPv6

The same IPv6 address can be written many ways. Store the canonical form:

a = ipaddress.ip_address("2001:0db8:0000:0000:0000:ff00:0042:8329")
str(a)        # '2001:db8::ff00:42:8329'
a.exploded    # '2001:0db8:0000:0000:0000:ff00:0042:8329'
Enter fullscreen mode Exit fullscreen mode

Comparing str() values after parsing avoids "duplicate" entries in your database.

Classifying addresses

Each address object exposes flags that answer the usual questions:

for v in ["10.0.0.5", "100.64.1.1", "127.0.0.1", "169.254.3.4",
          "8.8.8.8", "fe80::1", "::1", "2001:db8::1"]:
    ip = ipaddress.ip_address(v)
    print(v, ip.is_private, ip.is_global, ip.is_loopback, ip.is_link_local)
Enter fullscreen mode Exit fullscreen mode
Address private global loopback link-local
10.0.0.5 True False False False
100.64.1.1 False False False False
127.0.0.1 True False True False
169.254.3.4 True False False True
8.8.8.8 False True False False
fe80::1 True False False True
::1 True False True False
2001:db8::1 True False False False

Two interesting rows:

  • 100.64.1.1 is neither private nor global. It's in 100.64.0.0/10, the shared range used for carrier-grade NAT. If you're filtering "internal" traffic, don't rely on is_private alone.
  • 2001:db8::1 is flagged private because 2001:db8::/32 is reserved for documentation.

Results shown are from Python 3.13; the exact classification of a few special ranges has been refined across versions, so pin your Python version in tests that depend on it.

Unwrapping IPv4-mapped IPv6

Dual-stack servers often log IPv4 clients as ::ffff:a.b.c.d:

ip = ipaddress.ip_address("::ffff:192.0.2.128")
ip.ipv4_mapped   # IPv4Address('192.0.2.128')
Enter fullscreen mode Exit fullscreen mode

Normalise these before counting unique visitors or applying rate limits, or one client shows up twice.

Sorting and arithmetic

String sorting puts 10.0.0.100 before 10.0.0.9. Address objects sort numerically:

sorted(ipaddress.ip_address(x) for x in ["10.0.0.10", "10.0.0.9", "10.0.0.100"])
# [10.0.0.9, 10.0.0.10, 10.0.0.100]

ipaddress.ip_address("192.168.1.10") + 5          # 192.168.1.15
ipaddress.ip_address("192.0.2.1").reverse_pointer # '1.2.0.192.in-addr.arpa'
Enter fullscreen mode Exit fullscreen mode

TL;DR

  • Validate by parsing with ip_address() and catching ValueError.
  • Store str(ip) for a canonical form.
  • Use is_global for "is this a real internet address?", and handle 100.64.0.0/10 explicitly.
  • Unwrap ipv4_mapped before deduplicating.

No regex was harmed in the making of this post.

Top comments (0)