Sub topic 14
Checking your work with Python
Hand calculations are easy to get wrong by one bit or one block. This chapter shows how to use Python's standard ipaddress module to check them. It also shows how to turn a checked method into a repeatable test.
This chapter assumes you can already do the following by hand:
- Convert between binary and decimal for values 0 to 255.
- Read CIDR notation.
- Find network and broadcast addresses.
- Divide a block into subnets.
- Build a VLSM plan.
- Summarize routes.
You also need Python 3.9 or later. The module ships with Python, so there is nothing to install.
The checking workflow
Compute the answer by hand first, then ask the library, then compare. If you only copy the library's answer, you learn nothing and cannot spot an exam or design error later.
The core objects
The module has three main types. Each answers a different question.
| Type | Created with | Represents |
|---|---|---|
| `IPv4Address` | `ip_address("10.0.0.5")` | One address |
| `IPv4Network` | `ip_network("10.0.0.0/24")` | A whole subnet, with no host bits set |
| `IPv4Interface` | `ip_interface("10.0.0.5/24")` | A host address together with its prefix |
Use ip_interface when you start from a configured host address like 172.16.37.200/20. It keeps the host address and also gives you the subnet it belongs to.
import ipaddress
iface = ipaddress.ip_interface("172.16.37.200/20")
net = iface.network
print(iface.ip) # 172.16.37.200
print(net) # 172.16.32.0/20
print(net.netmask) # 255.255.240.0
print(net.network_address) # 172.16.32.0
print(net.broadcast_address) # 172.16.47.255
print(net.num_addresses) # 4096
hosts = list(net.hosts())
print(hosts[0], hosts[-1]) # 172.16.32.1 172.16.47.254
print(len(hosts)) # 4094Compare each line with your hand work. A mismatch usually points to one of three mistakes:
- The wrong block size in the interesting octet.
- Forgetting to subtract 2 for the network and broadcast addresses.
- A mask written with the wrong number of bits.
Strict mode catches host bits
ip_network refuses an address that has host bits set, because that is not a valid network address.
import ipaddress
try:
ipaddress.ip_network("192.168.10.5/24")
except ValueError as err:
print(err) # 192.168.10.5/24 has host bits set
print(ipaddress.ip_network("192.168.10.5/24", strict=False)) # 192.168.10.0/24This is useful as a check. If you wrote a network address by hand and the library rejects it, your address is not on a subnet boundary. Pass strict=False only when you want the library to compute the containing network for you.
Cross-checking the bitwise method
In the subnet mask chapter you found the network address with a bitwise AND. You can test that method against the library on thousands of random inputs. If your formula has a bug, an assertion fails.
import ipaddress
import random
random.seed(1)
for _ in range(10000):
ip = random.getrandbits(32)
prefix = random.randint(0, 32)
mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
network = ip & mask
broadcast = network | (~mask & 0xFFFFFFFF)
ref = ipaddress.ip_network((ip, prefix), strict=False)
assert network == int(ref.network_address)
assert broadcast == int(ref.broadcast_address)
assert (broadcast - network + 1) == ref.num_addresses
print("bitwise method agrees with ipaddress")The & 0xFFFFFFFF after the shift matters. Python integers have no fixed width, so a left shift would otherwise grow past 32 bits. Prefix 0 is included on purpose, because it is the edge case where the mask is all zeros.
Checking equal subnetting and summarization
Use subnets() to check a split. You can ask for a new prefix length, or for a number of extra bits.
import ipaddress
net = ipaddress.ip_network("192.168.10.0/24")
for sub in net.subnets(new_prefix=26):
print(sub, sub.network_address, sub.broadcast_address)
print(list(net.subnets(prefixlen_diff=1)))
# [IPv4Network('192.168.10.0/25'), IPv4Network('192.168.10.128/25')]The reverse operation is supernet(), which gives the parent block. For summarization use collapse_addresses(), which merges every group of contiguous, aligned blocks it can.
import ipaddress
blocks = [ipaddress.ip_network(f"192.168.{i}.0/24") for i in range(4)]
print(list(ipaddress.collapse_addresses(blocks)))
# [IPv4Network('192.168.0.0/22')]
# Not aligned: 1.0 to 4.0 cannot form one /22.
shifted = [ipaddress.ip_network(f"192.168.{i}.0/24") for i in range(1, 5)]
print(list(ipaddress.collapse_addresses(shifted)))
# [IPv4Network('192.168.1.0/24'), IPv4Network('192.168.2.0/23'), IPv4Network('192.168.4.0/24')]The second result shows the alignment rule from the block size chapter. Four contiguous /24 networks only summarize to a single /22 if the first one starts on a multiple of 4 in the third octet. Here the first starts at 1, so the best the library can do is three routes.
Two more helpers answer "does this fit" questions:
a.subnet_of(b)is true whenalies entirely insideb.a.overlaps(b)is true when the two share any address.
Validating a VLSM plan
A VLSM plan has three rules: every subnet fits in the pool, every subnet has enough usable hosts, and no two subnets overlap. You can check all three in one function. The function returns a list of problems, so an empty list means the plan is valid.
import ipaddress
from itertools import combinations
def check_plan(pool_cidr, plan):
pool = ipaddress.ip_network(pool_cidr)
nets = {name: (ipaddress.ip_network(cidr), need)
for name, (cidr, need) in plan.items()}
problems = []
for name, (net, need) in nets.items():
if not net.subnet_of(pool):
problems.append(f"{name}: {net} is outside {pool}")
usable = net.num_addresses - 2
if usable < need:
problems.append(f"{name}: {net} has {usable} usable, needs {need}")
for (n1, (a, _)), (n2, (b, _)) in combinations(nets.items(), 2):
if a.overlaps(b):
problems.append(f"{n1} {a} overlaps {n2} {b}")
return problems
good = {"A": ("192.168.1.0/25", 100), "B": ("192.168.1.128/26", 50),
"C": ("192.168.1.192/27", 20), "D": ("192.168.1.224/30", 2)}
bad = {"A": ("192.168.1.0/25", 100), "B": ("192.168.1.64/26", 50),
"C": ("192.168.1.192/28", 20)}
print(check_plan("192.168.1.0/24", good)) # []
for p in check_plan("192.168.1.0/24", bad):
print(p)
# B: 192.168.1.64/26 overlaps ... (see output)Run it and read the output. For the bad plan you get an overlap between A and B, and a capacity error for C, because a /28 has only 14 usable addresses. The subtraction of 2 is correct here. For /31 and /32 it is not, which the next section covers.
Longest-prefix match
You can model a routing table as a dictionary from network to next hop. The lookup keeps every route that contains the destination and picks the one with the longest prefix.
import ipaddress
routes = {
ipaddress.ip_network("0.0.0.0/0"): "default",
ipaddress.ip_network("10.0.0.0/8"): "core",
ipaddress.ip_network("10.1.0.0/16"): "branch",
ipaddress.ip_network("10.1.2.0/24"): "lab",
}
def lookup(dest):
addr = ipaddress.ip_address(dest)
matches = [net for net in routes if addr in net]
best = max(matches, key=lambda net: net.prefixlen)
return best, routes[best]
for dest in ["10.1.2.9", "10.1.9.1", "10.200.0.1", "8.8.8.8"]:
print(dest, *lookup(dest))
# 10.1.2.9 10.1.2.0/24 lab
# 10.1.9.1 10.1.0.0/16 branch
# 10.200.0.1 10.0.0.0/8 core
# 8.8.8.8 0.0.0.0/0 defaultThe default route matches every address, so matches is never empty. In a table without a default route, max would raise an error for an unreachable destination. Real routers drop the packet in that case.
Gotchas
- Usable hosts for /31 and /32.
num_addresses - 2is wrong for these prefixes. A /31 has 2 addresses, both usable on point-to-point links. A /32 has 1. Thehosts()method returns both addresses for a /31 and the single address for a /32, so preferhosts()over your own subtraction. hosts()is lazy. It returns an iterator. Wrapping a /8 inlist()builds over sixteen million objects. Usenum_addressesfor counts.- Strings compare as text.
"10.0.0.9" > "10.0.0.10"is true because string comparison is character by character. Compareip_addressobjects instead. - Mixed versions. You cannot compare or combine IPv4 and IPv6 objects. Doing so raises
TypeError. is_privateis broader than RFC 1918. It is also true for ranges such as 127.0.0.0/8 and 169.254.0.0/16. To test only the three RFC 1918 blocks, check membership in10.0.0.0/8,172.16.0.0/12and192.168.0.0/16yourself.- The library cannot check your intent. It confirms the arithmetic. It cannot tell you that a plan has too little room for growth, or that you picked the wrong host requirements.
Exercise
Exercise
You planned to summarize 10.4.0.0/24, 10.4.1.0/24, 10.4.2.0/24 and 10.4.3.0/24 as one route. Which call would verify it, what result do you expect, and what result would you get if the first block were 10.4.1.0/24 instead (four blocks from 10.4.1.0 to 10.4.4.0)?
Show answer
Call list(ipaddress.collapse_addresses(blocks)) on the four network objects. You expect [IPv4Network('10.4.0.0/22')], because 0 is a multiple of 4 in the third octet and the four blocks fill the /22 exactly. With blocks from 10.4.1.0 to 10.4.4.0, the range is not aligned. The result is three networks: 10.4.1.0/24, 10.4.2.0/23 and 10.4.4.0/24. No single route covers exactly those four blocks.
Exercise
Write a short check that confirms 172.20.5.77/27 belongs to the subnet 172.20.5.64/27, and print that subnet's first and last usable host.
Show answer
import ipaddress iface = ipaddress.ipinterface("172.20.5.77/27") net = ipaddress.ipnetwork("172.20.5.64/27") print(iface.network == net) # True hosts = list(net.hosts()) print(hosts[0], hosts[-1]) # 172.20.5.65 172.20.5.94 The block size of a /27 is 32, so subnets in the last octet start at 0, 32, 64, 96. The address .77 falls in the block starting at .64, whose broadcast address is .95.