IP Addresses & Subnets
Firewall rules, access lists, log analysis and incident response all talk in IP addresses and subnets. Python's standard ipaddress module understands both IPv4 and IPv6, so you can experiment safely without touching a network.
IPv4 and IPv6
An IPv4 address is a 32-bit number, written as four decimal bytes: 192.168.1.20. There are only about 4.3 billion of them, which is why IPv6 (128 bits, written in hex groups like 2001:db8::20) was introduced.
import ipaddress
v4 = ipaddress.ip_address("192.168.1.20")
v6 = ipaddress.ip_address("2001:db8::20")
print(v4.version, int(v4))
print(v6.version, v6.exploded)
print(ipaddress.ip_address(3232235796)) # the same IPv4 address as a number4 3232235796
6 2001:0db8:0000:0000:0000:0000:0000:0020
192.168.1.20
Because an address is just a number, tricks like writing http://3232235796/ instead of http://192.168.1.20/ are sometimes used to sneak past naive filters. Always parse addresses with a real library before comparing them.
Networks and CIDR notation
A subnet is a block of consecutive addresses. CIDR notation writes it as address/prefix: the prefix says how many leading bits are fixed. /24 fixes 24 bits and leaves 8 bits (256 addresses) for hosts.
import ipaddress
net = ipaddress.ip_network("10.20.30.0/24")
print("network: ", net.network_address)
print("broadcast:", net.broadcast_address)
print("netmask: ", net.netmask)
print("addresses:", net.num_addresses)
hosts = list(net.hosts())
print("first host:", hosts[0], " last host:", hosts[-1])
for prefix in (8, 16, 24, 28, 30, 32):
n = ipaddress.ip_network(f"10.0.0.0/{prefix}")
print(f"/{prefix:<2} -> {n.num_addresses:>10,} addresses")network: 10.20.30.0
broadcast: 10.20.30.255
netmask: 255.255.255.0
addresses: 256
first host: 10.20.30.1 last host: 10.20.30.254
/8 -> 16,777,216 addresses
/16 -> 65,536 addresses
/24 -> 256 addresses
/28 -> 16 addresses
/30 -> 4 addresses
/32 -> 1 addresses
The first address of a subnet is the network itself and the last is the broadcast address, so a /24 has 254 usable hosts.
Special address ranges
Some ranges have special meaning. Security tools treat them differently, and so should your code.
| Range | Meaning |
|---|---|
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 |
Private (RFC 1918), not routed on the internet |
127.0.0.0/8, ::1 |
Loopback: "this machine" |
169.254.0.0/16 |
Link-local; cloud metadata services live at 169.254.169.254 |
0.0.0.0 |
"Any address" when a server listens on it |
224.0.0.0/4 |
Multicast |
import ipaddress
samples = ["8.8.8.8", "10.1.2.3", "127.0.0.1", "169.254.169.254", "172.20.0.5", "::1"]
for text in samples:
ip = ipaddress.ip_address(text)
kind = ("loopback" if ip.is_loopback else
"link-local" if ip.is_link_local else
"private" if ip.is_private else
"global" if ip.is_global else "other")
print(f"{text:<16} {kind}")8.8.8.8 global
10.1.2.3 private
127.0.0.1 loopback
169.254.169.254 link-local
172.20.0.5 private
::1 loopback
You will meet this check again in the Input Validation lesson: a server that fetches URLs on behalf of users must refuse internal addresses, or attackers can use it to reach systems behind the firewall (this is called server-side request forgery, SSRF).
Membership tests for allow-lists
A very common security task is "is this client inside an allowed network?". The in operator does it correctly:
import ipaddress
office_networks = [
ipaddress.ip_network("203.0.113.0/26"),
ipaddress.ip_network("198.51.100.128/25"),
]
def from_office(addr):
ip = ipaddress.ip_address(addr)
return any(ip in net for net in office_networks)
for client in ["203.0.113.10", "203.0.113.70", "198.51.100.200", "198.51.100.5"]:
print(client, "allowed" if from_office(client) else "denied")203.0.113.10 allowed
203.0.113.70 denied
198.51.100.200 allowed
198.51.100.5 denied
Warning: Never compare addresses as strings, e.g.
addr.startswith("203.0.113."). That accepts203.0.113.200even when only/26(addresses.0–.63) is allowed, and misses equivalent spellings.
Splitting and summarising
Network engineers split a large block into smaller ones (for example, one subnet per department) and summarise many small ones into a single rule:
import ipaddress
block = ipaddress.ip_network("192.168.8.0/22")
for sub in block.subnets(new_prefix=24):
print(sub)
pieces = [ipaddress.ip_network(n) for n in
["10.0.0.0/25", "10.0.0.128/25", "10.0.1.0/24"]]
print(list(ipaddress.collapse_addresses(pieces)))192.168.8.0/24
192.168.9.0/24
192.168.10.0/24
192.168.11.0/24
[IPv4Network('10.0.0.0/23')]
Smaller subnets support network segmentation: putting servers, staff laptops, guests and IoT devices in separate subnets with firewall rules between them, so a compromised smart TV cannot reach the payroll server.
Go further: CIDR and Subnetting for Analysts has a bit-by-bit subnet lab and uses
ipaddressfor scope checks and incident summaries.
Test yourself
How many addresses does a /28 network contain?
- 8
- 16
- 28
- 256
Which address is private (RFC 1918)?
- 8.8.8.8
- 172.20.0.5
- 203.0.113.10
- 1.1.1.1
Why is addr.startswith("203.0.113.") a bad allow-list check for 203.0.113.0/26?
- It is too slow
- It also accepts addresses outside the /26 such as 203.0.113.200
- It only works for IPv6
- startswith is case-sensitive