Skip to content

Longest-prefix match for address ranges

An address can sit inside several listed ranges at once; longest-prefix match picks the one with the most leading bits fixed. It's how routers forward, and how a denylist holds exceptions yet answers in a few memory reads.

On this page

What it is

A range of IP addresses is written as a network address and a prefix length: 10.0.0.0/8 is the block whose first 8 bits equal those of 10.0.0.0, and 10.1.0.0/16 fixes the first 16. The two overlap, so the address 10.1.2.3 is inside both. Longest-prefix match is the rule for that situation: among the ranges that contain an address, the one with the longest prefix, the most specific, decides. Internet forwarding follows this rule, which is why a router with both blocks in its table sends 10.1.2.3 where the /16 says. A default route, with a prefix of zero bits, is the catch-all that applies when nothing longer matches.

The trie walk. The classic structure is a trie over the bits of the address, where each node's path from the root spells a prefix and its depth is the prefix length. A lookup reads the address one bit at a time: bit 0 goes to the first child, bit 1 to the second. Whenever the current node holds an entry, remember it as the best so far; when the needed child is missing, the walk ends and the best so far is the answer. The number of steps is capped by the address width, 32 for IPv4, so it doesn't grow with the size of the list. Routing software such as Quagga has used this plain form.

Compressing the walk. Most nodes in a plain trie have one child, which wastes steps and memory. Path compression removes those nodes and records on each survivor how many input bits to skip; the result is a Patricia trie or radix tree, used by the BSD routing tables. Because skipped bits were not compared, a match must be confirmed against the full stored prefix at the end, and a failed check is treated as a miss that backtracks to a shorter entry. The Linux kernel goes further with level compression: an internal node can hold an array of children indexed by several bits at once, and the array is grown or halved as entries come and go. Its lookup descends to a leaf, checks the leaf's entries sorted by prefix length, and on a miss backtracks with ever shorter prefix lengths until something matches.

Measured on Linux 4.11 (2017)Value

Maximum trie depth, full IPv4 Internet table

About 6 levels

One route lookup, full table

About 50 ns

Memory, full table

About 64 MiB

Memory, about 2 million routes

About 256 MiB, growing linearly with entries

A hash per prefix length. When the list uses few distinct prefix lengths, a hash table keyed by (masked address, length) is simpler than a trie. The lookup masks the address to each length present in the set, most specific first, and probes once per length, so its cost grows with the number of distinct lengths rather than with the number of entries. This is how the hash:net set type in the netfilter ipset tool works; it also accepts entries flagged nomatch, which punch an exception into a larger listed block, and it refuses a zero-length prefix, so there is no catch-all entry.

IPv6 changes the key, not the idea. IPv6 addresses are 128-bit identifiers, written with the same address/prefix-length notation, so a trie over them can reach four times the depth of an IPv4 one and each stored key is 16 bytes. The addressing architecture also requires a 64-bit interface identifier for unicast addresses outside the small block starting with binary 000, which means one subnet holds 2^64 addresses. A list of single IPv6 addresses therefore says little about who is behind them; a /64 is usually the smallest unit worth listing.

When to use it

Reach for longest-prefix match when ranges overlap and the verdict depends on the most specific one. The clearest case is an exception: a partner's /28 that must stay allowed inside a provider's /16 you deny, which the nomatch flag models as a more specific entry that is skipped at match time. A second case is ranges with different actions or metadata, such as a country or a hosting provider per block, where the answer is the entry itself and not a yes or no. A third is a default entry that applies to anything no longer prefix covers.

Use it, too, when the check sits on the request path and has to run from local memory. A trie or a per-length hash answers in a bounded number of steps set by the address width or by the count of prefix lengths, independent of how many entries are loaded, and a compressed trie keeps millions of IPv4 entries in a few hundred MiB. Our advice for an interview: name the prefix lengths your list actually contains (for example /32 and /24 for IPv4, /64 and /48 for IPv6), because that count drives the probe cost of the hash approach and is one of the things, along with how much the prefixes share, that sets the depth of the trie.

When not to

If each range carries the same verdict and there are no exceptions, you don't need the longest match, just any match. Then you can stop at the first hit, or go further: merge overlapping ranges into sorted, non-overlapping intervals of start and end addresses and binary search them. That structure is two integers per interval and no tree at all, and it suits a list that is rebuilt wholesale on each update rather than edited in place. A short list that rarely changes can simply be scanned.

User IDs, emails and other exact keys are not ranges. Our advice: keep them in an ordinary hash set, with a Bloom filter in front if you want a cheap first pass, and put address ranges in their own structure; a trie keyed on an email adds depth for nothing. And if the list lives in a firewall whose set types already do prefix matching, as the netfilter sets do, an application-level copy is extra work unless the application needs the answer itself.

Compared

StructureLookup costMemoryPick it when

Linear scan of ranges

One comparison per range

The ranges themselves

A few dozen ranges, or a prototype you'll replace

Plain binary trie

Up to one step per address bit (32 for IPv4)

Up to one node per bit of each prefix; shared leading bits share nodes

The list is small and the code must be obvious

Path-compressed trie (Patricia, radix)

Fewer steps, plus a final compare of the full prefix

Single-child nodes removed unless they hold an entry

A general-purpose list with exceptions and metadata

Level-compressed trie (Linux LPC-trie)

About 6 levels and about 50 ns for a full IPv4 table

About 64 MiB for a full table, linear in entries

Millions of entries with lookups on the hot path

Hash table per prefix length

One probe per distinct prefix length, most specific first

One hash entry per range

The list uses a handful of lengths; exceptions via a no-match flag

Sorted disjoint intervals, binary search

Logarithmic in the number of intervals

Two addresses per interval

One verdict, no exceptions, rebuilt wholesale

In a picture

first 8 bitsother bitsnext 8 bitsno childLook up 10.1.2.3Root: no entry10.0.0.0/8: denyOther blocks10.1.0.0/16: allowDeepest entrywins: allow
The walk passes the /8 deny entry, then the /16 allow entry, and stops when no child matches; the deepest entry passed is the answer.

How to say it in an interview

The common mistake

Quiz

A list denies 10.0.0.0/8 and allows 10.1.0.0/16. A request arrives from 10.1.2.3. What does longest-prefix match decide?
A list holds a million ranges, but they use just four prefix lengths: /32, /24, /64 and /48. With a hash table per prefix length, how many probes can one lookup need at most?
Why does a path-compressed trie check the bits of the found entry's prefix against the address at the end of a lookup?
When is longest-prefix match unnecessary for an address list?

Questions that use this

Hear it in

Related

Sources

  1. RFC 4632: Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan
  2. RFC 4291: IP Version 6 Addressing Architecture
  3. Wikipedia: Longest prefix match
  4. The Linux Kernel documentation: LC-trie implementation notes
  5. ipset(8) man page: administration tool for IP sets
  6. Vincent Bernat: IPv4 route lookup on Linux
Sign in to report a mistake