CNComputer Networks

Block B · Topics 4–11

IP & routing

The layer that makes it one internet rather than millions of separate networks. IP promises almost nothing — best effort, no ordering, no delivery guarantee — and that minimalism is exactly why it scaled.

04

IP addressing

IPv4 headerTTLfragmentationprivate ranges
Why it exists

MAC addresses are flat and globally unique, which makes them useless for routing — no router could hold a table of every device on earth. IP addresses are hierarchical: the prefix identifies a network, so a router only needs to know "everything starting 142.250 goes that way". Hierarchy is what makes a routing table finite.

The IPv4 header

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
┌───────┬───────┬───────────────┬───────────────────────────────┐
│version│  IHL  │      TOS      │        total length           │
├───────┴───────┴───────────────┼─┬─┬─┬─────────────────────────┤
│         identification        │0│D│M│     fragment offset     │
├───────────────┬───────────────┼─┴─┴─┴─────────────────────────┤
│      TTL      │   protocol    │        header checksum        │
├───────────────┴───────────────┴───────────────────────────────┤
│                      source IP address                       │
├───────────────────────────────────────────────────────────────┤
│                    destination IP address                     │
└───────────────────────────────────────────────────────────────┘
                        20 bytes minimum

The fields that get asked about:
  TTL         decremented by EVERY router; at 0 the packet is dropped and
              an ICMP "time exceeded" is returned. Stops routing loops from
              circulating forever — and is exactly what traceroute exploits.
  protocol    1 = ICMP, 6 = TCP, 17 = UDP. How the receiver knows which
              transport layer to hand the payload to.
  DF / MF     Don't Fragment / More Fragments — the fragmentation controls.
  checksum    covers the HEADER ONLY, not the payload, and must be
              recomputed at every hop because TTL changed. IPv6 dropped it
              entirely, on the grounds that layer 2 and layer 4 both check.
Fragmentation, and why it's considered harmful

If a packet exceeds the next link's MTU, an IPv4 router may split it into fragments that are only reassembled at the final destination. The problem: losing any single fragment means the whole original packet is lost, so loss probability multiplies; reassembly costs memory and is a DoS vector; and intermediate firewalls can't inspect ports on non-first fragments.

So modern practice sets DF and relies on Path MTU Discovery — the router returns ICMP "fragmentation needed" and the sender shrinks its packets. IPv6 removed router fragmentation altogether. The failure mode to remember: if a firewall blocks ICMP, PMTUD breaks silently and you get a connection that establishes and then hangs on the first full-size packet.

Special and private ranges

RangeMeaning
10.0.0.0/8Private (16.7M addresses) — big corporate and cloud VPCs
172.16.0.0/12Private (1M) — 172.16172.31, a common exam trap
192.168.0.0/16Private (65k) — home routers
127.0.0.0/8Loopback. The whole /8, not just 127.0.0.1.
169.254.0.0/16Link-local. Seeing this means DHCP failed. (Also cloud metadata at 169.254.169.254.)
224.0.0.0/4Multicast
255.255.255.255Limited broadcast — this link only, never forwarded
0.0.0.0/0"Any address" — as a route, the default route

Classful addressing (A/B/C) is worth knowing only as history: fixed 8/16/24-bit boundaries meant an organisation needing 300 addresses got a class B with 65,534 and wasted 65,000 of them. CIDR replaced it in 1993 with arbitrary prefix lengths, which is the direct reason IPv4 lasted decades longer than predicted.

05

Subnetting & CIDR

masksprefix mathsVLSMworked examples
Why it exists

Two reasons: conserving addresses (give each network exactly what it needs) and limiting broadcast domains (a flat network of thousands of hosts drowns in ARP). Subnetting is also the most reliably examined topic in networking, because it's objectively markable — so it is worth being fast at.

The mechanics

An address is 32 bits split by the prefix length /n:
the first n bits are the network, the remaining 32−n are the host.

total addresses = 2(32−n)
usable hosts = 2(32−n) − 2  (subtract the network address and the broadcast address)
block size (the step between subnets) = 256 − (the interesting octet of the mask)
CIDRMaskAddressesUsableTypical use
/8255.0.0.016,777,21616,777,214A whole private range
/16255.255.0.065,53665,534A large VPC
/24255.255.255.0256254A typical LAN
/25255.255.255.128128126Half a /24
/26255.255.255.1926462A department
/27255.255.255.2243230A small subnet
/28255.255.255.2401614A rack of servers
/30255.255.255.25242A point-to-point link
/31255.255.255.25422 (RFC 3021)Modern point-to-point
/32255.255.255.25511A single host route

Worked example 1 — find the subnet for an address

Given  192.168.10.130/26   →  which subnet, and what's the range?

/26 → mask 255.255.255.192 → block size = 256 − 192 = 64
Subnets step in 64s:   .0   .64   .128   .192
130 falls in the .128 block (128 ≤ 130 < 192)

  Network address    192.168.10.128     # all host bits 0 — not usable
  First usable host  192.168.10.129
  Our address        192.168.10.130 ✓
  Last usable host   192.168.10.190
  Broadcast          192.168.10.191     # all host bits 1 — not usable
  Usable hosts       2⁶ − 2 = 62

The fast method, no binary needed:
  1. block size = 256 − mask octet
  2. count up in block-size steps until you pass the address
  3. step back one → that's the network address
  4. next network − 1 = broadcast; network+1 .. broadcast−1 = usable

Worked example 2 — VLSM, the realistic version

You have 192.168.1.0/24. You need:
   Sales 100 hosts · Engineering 50 · Ops 25 · two WAN links of 2

Rule: always allocate LARGEST FIRST, or you fragment the space and get stuck.

Sales    needs 100 → 2⁷−2 = 126 ≥ 100 → /25 (128 addrs)
  192.168.1.0/25      usable .1 – .126        broadcast .127

Eng      needs 50  → 2⁶−2 = 62 ≥ 50   → /26 (64 addrs)
  192.168.1.128/26    usable .129 – .190      broadcast .191

Ops      needs 25  → 2⁵−2 = 30 ≥ 25   → /27 (32 addrs)
  192.168.1.192/27    usable .193 – .222      broadcast .223

WAN 1    needs 2   → /30 (4 addrs)
  192.168.1.224/30    usable .225 – .226      broadcast .227
WAN 2    needs 2   → /30
  192.168.1.228/30    usable .229 – .230      broadcast .231

Remaining: 192.168.1.232 – .255 free for growth.

If you had allocated Ops first at .0/27, Sales would then need a
128-aligned /25 and .0/25 is already partly used — you'd have to jump to
.128/25, wasting the whole first block. Alignment matters: a /25 must
start at .0 or .128, a /26 at a multiple of 64, and so on.
Exam traps
  • Forgetting the −2. A /24 has 256 addresses and 254 usable hosts.
  • Cloud providers reserve more. AWS takes 5 addresses per subnet (network, broadcast, gateway, DNS, one reserved), so an AWS /24 gives 251 usable. Mentioning this reads as practical experience.
  • Alignment. 192.168.1.100/26 is a valid host address but 192.168.1.100 is not a valid /26 network address — networks must sit on block-size boundaries.
  • Supernetting is the reverse. Four contiguous, aligned /24s aggregate into one /22 — which is how BGP keeps the global table from exploding.
06

NAT

PATprivate address spaceport translationwhat it breaks
Why it exists

IPv4 has 4.3 billion addresses and the world has far more devices. NAT lets an entire household or company share one public address by rewriting addresses and ports at the boundary. It bought IPv4 an extra two decades — and in doing so it broke the internet's original end-to-end model, which is why so many protocols have awkward workarounds.

How it actually works (PAT / NAPT)

Laptop 192.168.1.10:51000  →  google.com 142.250.183.14:443

Router rewrites the SOURCE and records the mapping:
  ┌─────────────────────┬──────────────────────┬─────────────────────┐
  │ inside              │ outside (public)     │ destination         │
  ├─────────────────────┼──────────────────────┼─────────────────────┤
  │ 192.168.1.10:51000  │ 203.0.113.7:62145    │ 142.250.183.14:443  │
  │ 192.168.1.11:51000  │ 203.0.113.7:62146    │ 142.250.183.14:443  │
  └─────────────────────┴──────────────────────┴─────────────────────┘
     ↑ two devices, identical inside ports — the PUBLIC PORT disambiguates

Reply arrives at 203.0.113.7:62145 → look up the table → rewrite the
destination to 192.168.1.10:51000 → forward inside.

This is why it's really PORT address translation: one public IP can
multiplex ~64,000 concurrent flows because the port field is the key.
Entries expire on a timer (TCP idle timeouts are often 5–30 min, UDP
much shorter — which is why long-lived idle connections silently die
behind NAT and why applications send keepalives).
TypeMappingUse
Static NATOne private ↔ one public, permanentlyPublishing an internal server
Dynamic NATPrivate → any free public from a poolRare now
PAT / NAPTMany private → one public, via portsEssentially all home and office internet
Port forwardingAn inbound public port → a fixed internal hostSelf-hosting behind NAT
CGNATISP-level NAT — subscribers share public IPsMobile networks; breaks inbound entirely
What NAT breaks — the interesting half of the question
  • Inbound connections. There's no table entry until you send something out, so nobody can initiate a connection to you. This is why peer-to-peer, VoIP and gaming need STUN (discover your public mapping), TURN (relay through a server when hole-punching fails), or UPnP.
  • Protocols that embed IP addresses in their payload. Active FTP and SIP put addresses inside the message body, which NAT doesn't rewrite, so they need protocol-specific helpers (ALGs).
  • End-to-end integrity. IPsec AH authenticates the header, which NAT modifies — hence NAT-Traversal encapsulating IPsec in UDP.
  • Attribution and rate limiting. Thousands of users share one IP, so per-IP rate limiting punishes a whole carrier's customers. This is a real system-design consequence, not just trivia.

And to say clearly: NAT is not a firewall. It happens to block unsolicited inbound traffic as a side effect of having no mapping, but it enforces no policy — it doesn't inspect anything, and once a mapping exists traffic flows. Treating it as security is a common and marked-down mistake.

07

Routing & forwarding

longest prefix matchdefault routeforwarding table
Why the distinction matters

Routing is the control plane: protocols exchanging information to build a picture of the network, on a timescale of seconds to minutes. Forwarding is the data plane: looking up a destination and moving a packet out of the right port, in nanoseconds, per packet. Different timescales, different hardware, and conflating them is a marked-down error.

Longest prefix match, worked

Routing table:
  10.0.0.0/8        → interface eth1
  10.1.0.0/16       → interface eth2
  10.1.5.0/24       → interface eth3
  0.0.0.0/0         → gateway 203.0.113.1   # default route

Packet for 10.1.5.99:
  matches /8   ✓  (10.x.x.x)
  matches /16  ✓  (10.1.x.x)
  matches /24  ✓  (10.1.5.x)   ← LONGEST prefix wins
  matches /0   ✓  (everything does)
  → forward out eth3

Packet for 10.1.9.4  → /16 is the longest match → eth2
Packet for 10.7.1.1  → /8  is the longest match → eth1
Packet for 8.8.8.8   → only the default route matches → gateway

Why longest wins: a longer prefix is a MORE SPECIFIC statement about the
network, so it reflects more precise knowledge. It's also what makes
hierarchy work — a provider can advertise one /16 while a customer
advertises a /24 inside it, and traffic still reaches the customer.

Reading a real routing table is a fair question:

$ ip route
default via 192.168.1.1 dev wlan0 proto dhcp metric 600
192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.20
// line 1: anything not matched below → the gateway
// line 2: this subnet is directly attached ("scope link") — no gateway
//         needed, just ARP for the destination and send the frame
Terms that get mixed up
  • Routing table (RIB) is what the protocols built, including alternatives. Forwarding table (FIB) is the optimised best-path-only copy the hardware actually uses, often in specialised memory (TCAM) so lookups take constant time.
  • Metric vs administrative distance. Metric compares routes within one protocol; administrative distance decides between protocols when both offer a route to the same prefix.
  • Static vs dynamic. Static routes are manual and don't react to failure; dynamic protocols reconverge but cost complexity and CPU.
  • ECMP — equal-cost multi-path — hashes each flow across several equal routes. Per-flow hashing rather than per-packet, so a TCP connection's packets don't arrive out of order.
08

Routing protocols

RIPOSPFBGPdistance vectorlink state
Why several exist

Because "find the best path" means different things inside one organisation versus between competing companies. Inside, you want the mathematically shortest path, fast. Between, you want the path that respects contracts, money and policy — and "shortest" is often not what anyone wants.

The two families

Distance vectorLink state
Each router knowsOnly distance + direction per destination ("trust my neighbours")The entire topology map
SharesIts whole table, with neighbours onlyIts local links, flooded to everyone
Computes withBellman-Ford, iterativelyDijkstra, locally on the full map
ConvergenceSlow; suffers count-to-infinityFast — everyone recomputes from the same map
Resource useLow CPU and memoryHigher CPU and memory
ExampleRIPOSPF, IS-IS

Count-to-infinity is the classic distance-vector failure: a network goes down, but A hears from B that B can reach it (via A), so A increments and believes B, and the cost climbs slowly toward infinity while packets loop. Mitigations: cap the metric (RIP's maximum is 15 hops, 16 = unreachable), split horizon (don't advertise a route back to the neighbour you learned it from), and route poisoning with triggered updates.

The three you should be able to compare

RIPOSPFBGP
TypeDistance vectorLink statePath vector
ScopeInterior (IGP)Interior (IGP)Exterior (EGP) — between autonomous systems
MetricHop countCost, derived from bandwidthPolicy: AS-path length, local preference, MED, communities
Scales to~15 hops. Tiny.A large enterprise, using areasThe entire internet — ~1M prefixes
TransportUDP 520Directly on IP (protocol 89)TCP 179
PicksFewest hops — ignores bandwidth, so it'll take a 1 Mbps single hop over two 10 Gbps hopsShortest weighted pathWhatever policy says — often the cheapest, not the fastest
StatusHistoricalStandard inside networksRuns the internet
BGP is the one worth understanding properly

BGP is path vector: an advertisement carries the full list of autonomous systems the route passes through. That gives loop detection for free — if I see my own AS number in the path, I reject it — and it makes policy expressible, because you can filter and prefer based on who is in the path.

The consequence to state: BGP optimises for business relationships, not latency. An ISP prefers routes through networks it doesn't pay for, so traffic between two Delhi users can transit Singapore because that's the cheaper peering arrangement. BGP is also built almost entirely on trust: it has no inherent verification that an AS is entitled to announce a prefix, which is why route hijacks happen — the 2008 Pakistan Telecom announcement that took YouTube offline globally, and the 2021 Facebook outage where withdrawn BGP routes made their DNS servers unreachable. RPKI is the ongoing fix.

09

ICMP & diagnostics

pingtracerouteTTL exceeded
Why it exists

IP has no way to report problems — a dropped packet is simply gone. ICMP is the control and error channel: unreachable destinations, expired TTLs, MTU too large. It carries no user data, and it is the mechanism behind both diagnostic tools you will be asked about.

How ping works

ICMP Echo Request (type 8)  →  target
ICMP Echo Reply   (type 0)  →  back

Measures RTT and loss. It does NOT use TCP or UDP — ICMP is its own
protocol directly on IP (protocol number 1), which is why ping has
no port number.

"Ping fails so the host is down" is wrong. Very common answer, marked down.
Many networks and cloud security groups block ICMP by default, so ping
failing proves only that ICMP echo isn't getting through. Test the actual
service instead: `curl` it, or `nc -zv host 443`.

How traceroute works — the clever bit

It exploits TTL. Send a packet with TTL=1:
  the FIRST router decrements it to 0, drops it, and returns
  ICMP Time Exceeded (type 11) — which reveals that router's address.
Then TTL=2 → the second router replies. TTL=3 → the third. And so on,
until the destination itself answers (Port Unreachable, or Echo Reply).

Reading the output honestly:
· `* * *` means that hop didn't return ICMP — usually a filtering router,
  NOT necessarily where traffic stops. Traffic may pass through fine.
· High latency at one hop that DOESN'T persist to later hops is normal:
  routers deprioritise generating ICMP replies. Only rising latency that
  CONTINUES to the end is real.
· Paths can differ per packet (ECMP), so consecutive hops may not lie on
  one actual path.
· The reverse path may differ from the forward path entirely.

Linux traceroute sends UDP to high ports by default; Windows tracert uses
ICMP Echo; `traceroute -T` uses TCP SYN, which is what you want when
ICMP and UDP are filtered. mtr runs it continuously — better for
intermittent problems.
ICMP messageMeansSeen when
Echo request / reply (8 / 0)Are you there?ping
Destination unreachable (3)No route, or port closedSub-codes distinguish network / host / port unreachable
Fragmentation needed (3, code 4)Too big and DF is setPath MTU discovery — blocking this causes silent hangs
Time exceeded (11)TTL hit zerotraceroute, and routing loops
Redirect (5)"Use a better gateway"Rare; often disabled as a security risk
Say this

"ping is ICMP echo request and reply — no ports, its own protocol on IP. traceroute exploits TTL: send TTL=1 and the first router returns time-exceeded revealing itself, then TTL=2 for the second, and so on. Two things I'd caution about reading its output: stars mean that hop didn't answer ICMP rather than that traffic stopped there, and a latency spike at one hop that doesn't persist to later hops is just that router deprioritising ICMP generation, not real delay."

10

DHCP

DORAleasesrelay
Why it exists

Manually assigning an address, mask, gateway and DNS server to every device is unmanageable and error-prone once you have more than a handful — and impossible for devices that come and go. DHCP does it automatically, and hands out far more than just an address.

DORA

DISCOVER  client → broadcast 255.255.255.255
           "I have no address (src 0.0.0.0), is there a DHCP server?"
OFFER     server → "you can have 192.168.1.50, mask /24,
                      gateway .1, DNS 8.8.8.8, lease 24h"
REQUEST   client → broadcast "I accept 192.168.1.50"
                      // broadcast, not unicast — so other servers
                      // that offered know their offer was declined
ACK       server → "confirmed, it's yours"

Then the client typically sends a gratuitous ARP to check nobody else
is already using the address.

Renewal: at 50% of the lease the client asks to renew (unicast); at
87.5% it broadcasts to any server; at 100% it must stop using the address.

Because DISCOVER is a broadcast it cannot cross a router. A DHCP RELAY
AGENT on each subnet forwards it as unicast to a central server — which
is how one server can address a whole campus.

Besides the address, DHCP options carry: subnet mask, default gateway,
DNS servers, NTP servers, domain name, MTU, and (option 66/67) the boot
server for PXE network booting.
The diagnostic worth knowing

An address in 169.254.0.0/16 means DHCP failed and the OS self-assigned a link-local address. Windows calls it APIPA. You'll have local connectivity and nothing else. Also worth naming: DHCP is unauthenticated, so a rogue DHCP server can hand out its own address as the gateway and become a man-in-the-middle. The mitigation is switch-level DHCP snooping.

11

IPv6

128-bitSLAACdual stackno NAT
Why it exists

IPv4's 4.3 billion addresses ran out — the last blocks were allocated in 2011. IPv6 has 2128 addresses, about 3.4×1038, which is enough to assign a /64 subnet to every grain of sand. But it also cleans up a lot of IPv4's accumulated awkwardness, and that's the more interesting half.

Address format

Full     2001:0db8:0000:0000:0000:ff00:0042:8329
Rules    · drop leading zeros in each group
         · replace ONE run of all-zero groups with ::
Short    2001:db8::ff00:42:8329

Loopback  ::1                (was 127.0.0.1)
Any       ::                 (was 0.0.0.0)
Link-local fe80::/10         — auto-configured, every interface has one
Unique local fc00::/7        — the rough equivalent of private ranges
Global unicast 2000::/3      — routable on the internet

Standard split: /64 network + /64 interface identifier.
A home connection is typically delegated a /56 or /48, giving you
hundreds or thousands of /64 subnets. There is no address scarcity to
manage, which is why subnetting IPv6 is about structure, not conservation.

What actually changed

IPv4IPv6Why
Address32 bits128 bitsExhaustion
Header20–60 B, variable40 B, fixedFixed size means faster hardware parsing; options moved to extension headers
ChecksumYes, recomputed each hopNoneLayer 2 and layer 4 already check — this removes per-hop work
FragmentationRouters may fragmentSender onlyRouters get simpler; PMTUD becomes mandatory
BroadcastYesNo — multicast onlyBroadcast wakes every host needlessly
ARPARPNDP (Neighbor Discovery, over ICMPv6)Integrated, and can be secured
AutoconfigurationNeeds DHCPSLAAC built inA host can configure itself from a router advertisement
NATUniversalUnnecessaryRestores end-to-end addressing — P2P and inbound connections just work
IPsecOptional add-onDesigned in (though still optional in practice)

SLAAC is the mechanism worth being able to describe: a host generates a link-local address, checks nobody else has it (duplicate address detection), then listens for a Router Advertisement carrying the /64 prefix and combines that prefix with an interface identifier to form a global address. No server, no state. Privacy extensions randomise the identifier so your MAC address isn't broadcast in every packet you send — the original scheme derived it from the MAC, which was a genuine tracking problem.

Why adoption took 25 years

IPv6 is not backwards compatible — an IPv6-only host cannot talk to an IPv4-only host, so there was never a moment when switching was individually rational. Everyone runs dual stack instead: both protocols side by side, with Happy Eyeballs in browsers racing an IPv4 and an IPv6 connection and using whichever answers first. NAT also removed the urgency by making IPv4 scarcity survivable. Transition mechanisms — NAT64/DNS64, 464XLAT, tunnelling — exist precisely because the clean cutover never happened.

Say this

"The headline is 128 bits instead of 32, but the design cleanups matter as much: a fixed 40-byte header so hardware can parse it without branching, no header checksum because layers 2 and 4 already verify, no router fragmentation, multicast instead of broadcast, and SLAAC so a host can configure itself from a router advertisement with no DHCP server. Adoption was slow because it isn't backwards compatible — there was never a point where one operator switching was rational — so everyone runs dual stack and browsers use Happy Eyeballs to race the two."