Longest prefix match

When routes overlap, a computer sends each packet by the most specific route that matches: the one with the longest prefix. This is how a VPN's routes sit beside the normal default route.

What to build

Pick the route for each destination by longest prefix match.

Requirements

  • Line 1: N. Then N routes CIDR interface, for example 0.0.0.0/0 wifi or 10.0.0.0/8 vpn.
  • Each remaining line is a destination address.
  • Among the routes whose block contains the address, choose the one with the largest prefix length; if two have the same length, take the one listed first.
  • Print ADDRESS via INTERFACE (CIDR), or ADDRESS unreachable if no route matches.

Input

As described.

Output

One line per destination.

Constraints

Up to 30 routes and 50 addresses, all valid.

Example

Input:

2
0.0.0.0/0 wifi
10.0.0.0/8 vpn
10.1.2.3
8.8.8.8

Output:

10.1.2.3 via vpn (10.0.0.0/8)
8.8.8.8 via wifi (0.0.0.0/0)

Why it works

A longer prefix describes a smaller, more specific network, so choosing the longest matching prefix sends traffic to the most specific route, which lets a VPN route for 10.0.0.0/8 win over a default route of 0.0.0.0/0.

Examples

Example 1 · Input
2
0.0.0.0/0 wifi
10.0.0.0/8 vpn
10.1.2.3
8.8.8.8
Expected output
10.1.2.3 via vpn (10.0.0.0/8)
8.8.8.8 via wifi (0.0.0.0/0)
Example 2 · Input
1
192.168.0.0/16 lan
192.168.5.5
10.0.0.1
Expected output
192.168.5.5 via lan (192.168.0.0/16)
10.0.0.1 unreachable

Hints

Hint 1

The prefix length is the number after the slash.

Hint 2

Keep the best match so far and replace it only when a new route's prefix is strictly longer.

Solution

Show one correct solution (try it yourself first)
function toNumber(ip) {
  const p = ip.split(".").map(Number);
  return ((p[0] * 256 + p[1]) * 256 + p[2]) * 256 + p[3];
}
function inBlock(ip, block) {
  if (block === "any") return true;
  const [base, bits] = block.split("/");
  const size = 2 ** (32 - Number(bits));
  return Math.floor(toNumber(ip) / size) === Math.floor(toNumber(base) / size);
}
const n = Number(prompt());
const routes = [];
for (let k = 0; k < n; k++) {
  const [cidr, iface] = prompt().trim().split(/\s+/);
  routes.push({ cidr, iface, bits: Number(cidr.split("/")[1]) });
}
let line = prompt();
while (line !== null) {
  const ip = line.trim();
  if (ip) {
    let best = null;
    for (const r of routes) if (inBlock(ip, r.cidr) && (!best || r.bits > best.bits)) best = r;
    console.log(best ? `${ip} via ${best.iface} (${best.cidr})` : `${ip} unreachable`);
  }
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: VPNs and secure tunnels →