Belajar
← All lessons

How NAT works

Out and back through the router

Laptop
Router
Server

router.js

// outbound: rewrite the source, remember the pairfunction outbound(pkt) {  const port = nextFreePort();  table.set(port, { inside: pkt.src, remote: pkt.dst });  pkt.src = `${PUBLIC_IP}:${port}`;  wan.send(pkt);} // inbound: only a known port gets throughfunction inbound(pkt) {  const row = table.get(pkt.dst.port);  if (!row) return; // no row: drop it, nobody inside asked for this  pkt.dst = row.inside;  lan.send(pkt);}

Fill the translation table then knock from outside

Open a connection to 203.0.113.10:443 from
NAT table on 198.51.100.7
A packet arrives for 198.51.100.7, portSent fromthe servera stranger

router.js

function inbound(pkt) {  const row = table.get(pkt.dst.port);  if (!row) return drop(pkt);  // a mapping only lets in the remote it was opened to  if (row.remote && row.remote !== pkt.src) {    return drop(pkt);  }  pkt.dst = row.inside;  lan.send(pkt);} // a port forward is a row you add by hand, open to anyonetable.set(8080, { inside: "192.168.1.20:80", remote: null });

Is this address private? type any IPv4 address

IPv4 address
Reserved ranges

ranges.js

const RESERVED = [  "10.0.0.0/8",      // RFC 1918  "172.16.0.0/12",   // RFC 1918  "192.168.0.0/16",  // RFC 1918  "100.64.0.0/10",   // CGNAT  "127.0.0.0/8",     // loopback  "169.254.0.0/16",  // link-local  "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", // docs];const isReserved = (ip) => RESERVED.some((r) => inPrefix(ip, r));

Topics

Next: How processes and threads work

Open lesson