Sub topic 6
Subnet Masks and Prefix Length
This chapter assumes you can read an IPv4 address in dotted decimal and binary, and that you know an address has a network part and a host part. It also assumes you have seen the classful default masks. Here you will learn how a mask marks the boundary between the two parts, how to write it as a prefix length, and how to apply it by hand and in code.
What a mask does
A subnet mask is a 32-bit number with the same shape as an IPv4 address. Each 1 bit in the mask marks a network bit in the address. Each 0 bit marks a host bit. The mask is not an address. It is a template laid over an address.
The classful defaults you saw in the previous chapter are masks too:
- Class A uses
255.0.0.0, which is 8 ones followed by 24 zeros. - Class B uses
255.255.0.0, which is 16 ones followed by 16 zeros. - Class C uses
255.255.255.0, which is 24 ones followed by 8 zeros.
A mask lets you place the boundary anywhere between bits, not only at the octet edges that classes used.
Prefix length notation
Writing four octets for a mask is tedious. The prefix length is a shorter notation that counts the leading 1 bits. 255.255.255.0 has 24 ones, so it is written /24. An address and its mask are written together as 192.168.1.130/26.
The two notations carry the same information. The prefix length is simply the number of network bits.
Valid masks are contiguous
A valid mask is a run of 1s followed by a run of 0s, with no mixing. That is why only nine values can appear in a mask octet:
| Octet value | Binary | Leading ones |
|---|---|---|
| 0 | 00000000 | 0 |
| 128 | 10000000 | 1 |
| 192 | 11000000 | 2 |
| 224 | 11100000 | 3 |
| 240 | 11110000 | 4 |
| 248 | 11111000 | 5 |
| 252 | 11111100 | 6 |
| 254 | 11111110 | 7 |
| 255 | 11111111 | 8 |
A mask such as 255.0.255.0 is invalid because its 1 bits are not contiguous. Once an octet is less than 255, every octet after it must be 0. For example, 255.255.192.0 is valid, and 255.255.192.255 is not.
Applying the mask with a bitwise AND
To find the network an address belongs to, combine the address and the mask with a bitwise AND. A result bit is 1 only when both input bits are 1. Network bits pass through unchanged, and host bits become 0.
Take 192.168.1.130 with mask 255.255.255.192 (/26). The first three octets are all ones in the mask, so they pass through. Only the last octet needs work:
address 130 = 10000010
mask 192 = 11000000
AND = 10000000 = 128The network address is 192.168.1.128, so the full network is 192.168.1.128/26. The host part is the leftover 00000010, which is 2.
Block size shortcut
When the boundary falls inside one octet, you can skip the binary. The block size is 256 minus the mask value in that octet. Networks start at multiples of the block size.
| Prefix | Mask | Host bits | Block size in last octet |
|---|---|---|---|
| /24 | 255.255.255.0 | 8 | 256 |
| /25 | 255.255.255.128 | 7 | 128 |
| /26 | 255.255.255.192 | 6 | 64 |
| /27 | 255.255.255.224 | 5 | 32 |
| /28 | 255.255.255.240 | 4 | 16 |
| /29 | 255.255.255.248 | 3 | 8 |
| /30 | 255.255.255.252 | 2 | 4 |
For /26 the block size is 64, so networks begin at 0, 64, 128 and 192. The address .130 lies between 128 and 191, so its network starts at .128. This matches the AND result.
The number of addresses in a network is 2 raised to the number of host bits. The next chapter explains why not all of them are usable by hosts.
Computing with code
The following functions convert a prefix to a mask, apply it, and validate a dotted mask.
import ipaddress
def prefix_to_mask(prefix):
if not 0 <= prefix <= 32:
raise ValueError("prefix must be between 0 and 32")
return (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
def to_int(text):
return int(ipaddress.ip_address(text))
def to_text(value):
return str(ipaddress.ip_address(value))
address = to_int("192.168.1.130")
mask = prefix_to_mask(26)
print(to_text(mask)) # 255.255.255.192
print(to_text(address & mask)) # 192.168.1.128
print(to_text(address & ~mask & 0xFFFFFFFF)) # 0.0.0.2The left shift places the ones at the top of the 32-bit value. The final & 0xFFFFFFFF keeps Python's unbounded integers within 32 bits. The same trim is needed on ~mask, because Python's ~ produces a negative number.
To go the other way, from a dotted mask to a prefix, check that the mask is contiguous first. Invert the mask. A contiguous mask inverts to a run of low ones such as 00000000 00000000 00000000 00111111. Adding 1 to such a value gives a power of two, which shares no bits with the original.
import ipaddress
def mask_to_prefix(text):
value = int(ipaddress.ip_address(text))
inverted = value ^ 0xFFFFFFFF
if inverted & (inverted + 1):
raise ValueError(text + " is not a contiguous mask")
return bin(value).count("1")
print(mask_to_prefix("255.255.255.0")) # 24
print(mask_to_prefix("255.255.240.0")) # 20
try:
mask_to_prefix("255.0.255.0")
except ValueError as error:
print(error) # 255.0.255.0 is not a contiguous maskUsing the standard library
In practice, use the ipaddress module. It separates two ideas that are easy to confuse: an interface (a host address plus its mask) and a network.
import ipaddress
iface = ipaddress.ip_interface("192.168.1.130/26")
print(iface.ip) # 192.168.1.130
print(iface.network) # 192.168.1.128/26
try:
ipaddress.ip_network("192.168.1.130/26")
except ValueError as error:
print(error) # 192.168.1.130/26 has host bits set
print(ipaddress.ip_network("192.168.1.130/26", strict=False)) # 192.168.1.128/26ip_network is strict by default. It rejects an address with non-zero host bits, because a network is identified by its network address. This error appears often in scripts that feed host addresses into network parsing. Use ip_interface when you have a host address, or pass strict=False when you intend to truncate.
How a host uses its mask
A host applies the mask to decide whether a destination is on its own network. It ANDs both its own address and the destination with its mask, then compares the results. If they match, the destination is local and the host sends directly. If they differ, the host sends the packet to its default gateway.
Suppose a host is 192.168.1.130/26. Its network is 192.168.1.128/26. A destination of 192.168.1.140 masks to .128, so it is local. A destination of 192.168.1.20 masks to .0, so it is not, even though the first three octets match. The host sends it to the gateway.
Edge prefixes
Three prefix lengths behave differently from the rest:
/0has no network bits. It matches every address and is how a default route is written, as0.0.0.0/0./32has no host bits. It names exactly one address and is used for host routes and loopback-style addresses on routers./31leaves one host bit. RFC 3021 permits it on point-to-point links, where both addresses are used by the two ends.
Wildcard masks
Some router access lists use a wildcard mask, which is the bitwise inverse of the subnet mask. The mask 255.255.255.192 becomes the wildcard 0.0.0.63. A 0 in a wildcard means "this bit must match" and a 1 means "ignore this bit". Do not confuse the two forms. Vendors differ in which one a command expects.
Common errors
- Non-contiguous mask. A value such as
255.255.192.255is invalid. Check that once an octet drops below 255, every later octet is 0. - Counting the prefix from the wrong end. The prefix counts ones from the left.
/26means 26 network bits, not 26 host bits. The host bits number 32 minus the prefix. - Comparing only the octets that look equal.
192.168.1.20and192.168.1.130share three octets but are on different/26networks. - Mismatched masks on one link. If two hosts on the same segment use different masks, they disagree about what is local. Traffic may work in one direction only.
- Host bits set in a network statement. Writing
192.168.1.130/26as a network is an error in strict tools. The network is192.168.1.128/26. - Assuming the class decides the mask. Classes give a default only. Today the mask is configured explicitly, and any prefix can be used with any address.
Exercise
A host has the address 10.4.77.200 with prefix /20. What is its mask, and what is its network address? What range of third-octet values belongs to that network?
Show answer
A /20 has 20 ones, so the first two octets are 255 and the third octet has 4 ones: 11110000 = 240. The mask is 255.255.240.0. The block size in the third octet is 256 - 240 = 16. The third octet 77 is 01001101, and ANDing with 11110000 gives 01000000 = 64. The network address is 10.4.64.0/20. The network covers third-octet values 64 to 79.
Exercise
Is 255.255.255.100 a valid subnet mask? Explain using binary.
Show answer
No. 100 is 01100100 in binary. A valid mask octet is a run of ones followed by a run of zeros, and 01100100 starts with a zero and then contains ones again. Only 0, 128, 192, 224, 240, 248, 252, 254 and 255 are valid values for a mask octet.