ipaddress.ip_address & properties
Classify an address
Lesson 5 of 20 · 9 min · Module 2: Python’s ipaddress toolkit
You now know how addresses work inside. In real code, Python’s ipaddress module does the careful work for you, for both IPv4 and IPv6.
Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Parse addresses with the ipaddress module
- Handle invalid input with try/except
- Order checks from most to least specific
The idea
ipaddress.ip_address(text) returns an address object or raises ValueError for invalid text. Objects have properties such as is_loopback (127.0.0.1, ::1) and is_private (10.x, 172.16-31.x, 192.168.x, IPv6 unique local addresses in fc00::/7, and other ranges not routed on the internet).
import ipaddress
address = ipaddress.ip_address("192.168.1.10")
print(address.version, address.is_private)
01One function, two versions
ip_address("::1") returns an IPv6Address and ip_address("10.0.0.1") an IPv4Address. Both have the same properties, so your code works for both.
import ipaddress
print(ipaddress.ip_address("::1").version)602Invalid input raises ValueError
Instead of returning None, ip_address raises ValueError for text such as "server". Catching it turns a crash into a clear answer.
03Most specific first
127.0.0.1 is both loopback and private. Checking is_loopback first gives the more useful, more specific label.
Your turn
classify(text) that returns "invalid" for text that is not an IP address, "loopback" for loopback addresses, "private" for other private addresses, and "public" for everything else. It must work for IPv4 and IPv6.What the checks look for
- Recognises loopback addresses in IPv4 and IPv6
- Recognises private addresses
- Recognises public addresses
- Reports invalid input instead of crashing
Take this with you
Let the ipaddress module parse and classify; your code decides what the result means.
Go a little further
Add a "link-local" category using is_link_local, for addresses such as 169.254.10.1 and fe80::1.