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 ipaddre
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
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
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
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'
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)
| 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 onis_privatealone. -
2001:db8::1 is flagged private because
2001:db8::/32is 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')
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'
TL;DR
- Validate by parsing with
ip_address()and catchingValueError. - Store
str(ip)for a canonical form. - Use
is_globalfor "is this a real internet address?", and handle100.64.0.0/10explicitly. - Unwrap
ipv4_mappedbefore deduplicating.
No regex was harmed in the making of this post.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.