ip_network & the in operator
Is it on my network?
Lesson 6 of 20 · 9 min · Module 2: Python’s ipaddress toolkit
Routers, firewalls, and VPNs constantly answer one question: which network does this address belong to?
Start this lesson →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…
- Create network objects
- Test whether an address belongs to a network
- Understand first-match order
The idea
ipaddress.ip_network("10.1.0.0/16") creates a network object. The in operator tests membership: ip_address("10.1.2.3") in ip_network("10.1.0.0/16") is True. By default, the network text must have no host bits set (10.1.0.0/16, not 10.1.2.3/16).
import ipaddress
net = ipaddress.ip_network("192.168.1.0/24")
print(ipaddress.ip_address("192.168.1.42") in net)
01Networks are ranges
ip_network("192.168.1.0/24") represents 256 addresses, from 192.168.1.0 to 192.168.1.255. The in operator checks whether an address falls inside that range.
02Overlapping networks
10.1.0.0/16 is inside 10.0.0.0/8. A router prefers the most specific route, but a simple list check returns whichever matching entry comes first, so order matters.
import ipaddress
print(ipaddress.ip_network("10.1.0.0/16").subnet_of(ipaddress.ip_network("10.0.0.0/8")))True03Mixing versions is safe
An IPv4 address is never inside an IPv6 network. The in operator simply returns False, so one list can mix both.
Your turn
find_network(address, networks). networks is a list of CIDR strings. Return the first network string that contains the address, or None if none does.What the checks look for
- Finds the matching network
- Returns the first match when networks overlap
- Returns None when nothing matches
- Works with IPv6
Take this with you
Convert once, then test membership with in.
Go a little further
Return the most specific matching network (the one with the longest prefix) instead of the first.