Sikau

Computer networks · Day 3 · about 35 min

Routing tables

Longest-prefix match: how a router picks the next hop.

Which way next?

A router doesn't know the whole path — only a routing table of prefixes and next hops. Several entries can match an address; the most specific (longest prefix) wins. The 0.0.0.0/0 entry matches everything: the default route, "send it up to my ISP".

Longest prefix match

const TABLE = [
  { prefix: "0.0.0.0/0", via: "isp" },     // the default route
  { prefix: "10.0.0.0/8", via: "core" },
  { prefix: "10.1.0.0/16", via: "office" },
  { prefix: "10.1.2.0/24", via: "lab" },
];

function route(table, ip) {
  let best = null;
  for (const r of table) {
    const bits = Number(r.prefix.split("/")[1]);
    if (inSubnet(ip, r.prefix) && (!best || bits > best.bits)) best = { bits, via: r.via };
  }
  return best ? best.via : null;
}

The rest of this lesson

  • Why the most specific route winsexplain
  • How tables get filledexplain
  • Pick the routepredict
  • Where does it go?match
  • Route lookupswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Computer networks