Belajar
← All lessons

How IP routing works

One packet, four hops

Laptop
R1
R2
R3
Server

laptop.js

// the laptop picks its first hop the same wayconst packet = { src, dst, ttl: 64, data };const route = lookup(dst, myRoutes);send(route.via ?? dst, packet);

router.js

// every router runs this for every packetfunction forward(packet) {  packet.ttl -= 1;  if (packet.ttl === 0) {    return icmp(packet.src, "Time Exceeded");  }  const route = lookup(packet.dst, routes);  if (!route) return icmp(packet.src, "Unreachable"); // no route at all  if (route.via) return send(route.via, packet);  send(packet.dst, packet); // direct route: the destination is on this link}

Longest prefix match type an address and see which route wins

Destination IP
Routing table
In binary, the bits each route checks

terminal

$ ip routedefault via 192.0.2.110.0.0.0/8 via 10.255.0.110.20.0.0/16 via 10.20.0.110.20.30.0/24 dev eth110.20.30.40/32 via 10.20.30.2

lookup.js

function lookup(dst, routes) {  let best = null;  for (const r of routes) {    // a /0 checks no bits, so it matches everything    const mask = r.len ? ~0 << (32 - r.len) : 0;    if ((dst & mask) !== (r.net & mask)) continue;    if (!best || r.len > best.len) best = r;  }  return best;}

TTL stops a packet that loops set it, then break a route

TTL the laptop sends4
What happens on the way

traceroute sends TTL 1, 2, 3 and so on. Each router that drops one replies, so you learn the path

router.js

function forward(packet) {  packet.ttl -= 1;  if (packet.ttl === 0) {    return icmp(packet.src, "Time Exceeded");  }  const route = lookup(packet.dst, routes);  send(route.via ?? packet.dst, packet);}

Topics

Next: How UDP works

Open lesson