Read a CIDR prefix and find which route matches an IPv4 address

Three overlapping blue blocks representing address ranges
Contents
  1. Convert the prefix length to a block
  2. Choose the longest matching route
  3. Recognize a device address written with a prefix
  4. Frequently asked questions

CIDR notation writes an IP block as an address followed by a slash and a prefix length. In IPv4, 192.0.2.0/24 fixes the first 24 of 32 bits and leaves eight to vary. You can use those fixed bits to find which route in a table applies to a destination.

Convert the prefix length to a block

For IPv4, subtract the prefix length from 32 to get the number of varying bits. A block then contains 2 raised to that number of addresses. Here is how that works when a prefix boundary falls in the last octet.

PrefixVarying bitsTotal addressesMatching range
192.0.2.0/248256192.0.2.0 through 192.0.2.255
192.0.2.64/26664192.0.2.64 through 192.0.2.127
192.0.2.70/3201192.0.2.70

For the /26, the block size is 64. Starting at 64 gives a final value of 64 + 64 − 1, or 127. That is the range of matching destination addresses. When assigning addresses on a subnet, check how the subnet mask and the IPv4 broadcast address affect host assignments.

Choose the longest matching route

Suppose a router has three routes: 192.0.2.64/26, 192.0.2.0/24, and 0.0.0.0/0. These examples use documentation addresses reserved by RFC 5737.

  • 192.0.2.70 matches all three. The /26 has the longest prefix, so it wins.
  • 192.0.2.130 falls outside the /26 but inside the /24. It uses the /24.
  • 198.51.100.10 matches only 0.0.0.0/0 in this table. It follows the default route.

RFC 4632 specifies forwarding by longest match. In a simple routing table, check membership first, then compare the lengths of only the matching routes.

Recognize a device address written with a prefix

An interface might display 192.0.2.70/26. The number before the slash is the device's IPv4 address. To refer to the whole block, set the varying bits to zero and write 192.0.2.64/26. You will see the block form in route tables.

Frequently asked questions

Does a larger slash number mean a larger range?

A longer prefix leaves fewer varying bits. In this example a /26 has 64 addresses, compared with 256 in a /24.

What does /0 mean?

The prefix fixes zero bits. In IPv4 a 0.0.0.0/0 route can match any destination. Another matching prefix with a greater length takes priority.

Sources