IP addresses and subnets

Read an IPv4 address and prefix

Interpret an IPv4 address together with its CIDR prefix length instead of treating the address alone as a network.

8 minute lesson

~~~

An IPv4 address contains 32 bits, usually written as four decimal numbers such as 192.0.2.34. Each number is one byte, 0 through 255. An interface also needs a prefix length, such as /24, and the address means very little without it.

The prefix length says how many leading bits identify the network. The remaining bits identify addresses inside that network. 192.0.2.34/24 belongs to the prefix 192.0.2.0/24: the first 24 bits (the first three numbers) name the network, and the last 8 bits name this particular host.

Look at your own interface and you’ll always find the two together:

ip -4 address show
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP>
    inet 192.168.1.20/24 brd 192.168.1.255 scope global dynamic eth0

The inet line is the fact that matters: this interface is 192.168.1.20, inside the network 192.168.1.0/24. On macOS, ifconfig en0 shows the same information as an address plus netmask 0xffffff00 — that hexadecimal mask is /24 written the old way, 24 one-bits followed by 8 zero-bits.

The prefix decides who’s local

Two addresses that look similar are not necessarily local neighbors. The prefix length determines whether the sender considers a destination on-link or sends it to a router.

Ask your kernel directly how it would reach two destinations:

ip route get 192.168.1.50
# 192.168.1.50 dev eth0 src 192.168.1.20

ip route get 192.168.2.50
# 192.168.2.50 via 192.168.1.1 dev eth0 src 192.168.1.20

192.168.1.50 matches your /24, so the answer has no via: deliver directly on the link. 192.168.2.50 differs in the third byte, falls outside the prefix, and gets a via 192.168.1.1 — hand it to the router. One byte of difference, a completely different delivery path.

Record both, always

Always write down an interface as address plus prefix. An address without its prefix is incomplete configuration information — you can’t tell which destinations are local, what the broadcast address is, or whether two machines should see each other directly.

A classic misconfiguration: two machines on the same cable, one set to /24 and the other to /16. Each computes a different idea of what’s local. Traffic flows one way but not the other, and everything half-works. Whenever direct communication between neighbors fails, compare prefixes first.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →