subnets(new_prefix) & num_addresses
Split a network into subnets
Lesson 7 of 20 · 10 min · Module 2: Python’s ipaddress toolkit
Network engineers rarely use one big network. They split it into smaller subnets: one per floor, team, or service.
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…
- Divide a network into equal subnets
- Read subnet boundaries
- Count addresses in a network
The idea
network.subnets(new_prefix=26) yields the smaller networks of the new size, in order. network.num_addresses is the total number of addresses. str(subnet) gives text such as "192.168.10.64/26".
import ipaddress
net = ipaddress.ip_network("192.168.10.0/24")
print([str(n) for n in net.subnets(new_prefix=25)])
01Each extra prefix bit halves the size
A /24 has 256 addresses. Two /25 networks have 128 each; four /26 networks have 64 each. Every subnet starts where the previous one ended.
import ipaddress
print(ipaddress.ip_network("192.168.10.0/26").num_addresses)6402subnets() is a generator
It produces subnets one at a time instead of building a list immediately. Wrapping it in a list comprehension collects all of them, which is fine for a handful of subnets.
03Boundaries follow powers of two
/26 networks in a /24 always start at .0, .64, .128, and .192. Recognising these steps makes routing tables and firewall rules much easier to read.
Your turn
split_network(cidr, new_prefix) that returns the list of subnet strings. Also write usable_hosts(cidr) that returns the number of usable host addresses for IPv4 networks with a prefix up to /30.What the checks look for
- Splits a /24 into four /26 networks
- Splits a /16 into /18 networks
- Counts usable hosts
Take this with you
Splitting a network is repeated halving; every subnet has the same size.
Go a little further
Return each subnet together with its usable host count as a tuple.