The Network Layer

The Internet layer is the "thin waist" of the internet's hourglass architecture: every application runs above it, every physical technology runs below it, and IP is the universal glue in the middle. It provides two services: logical addressing (globally unique identifiers for interfaces) and routing (getting packets from any source to any destination across an arbitrary number of hops).

IPv4 — Internet Protocol version 4 (RFC 791, 1981)

IPv4 is a connectionless, best-effort packet delivery protocol. "Best-effort" means IP does not guarantee delivery, order, or absence of duplicates — those guarantees are left to TCP if needed.

IPv4 header (20 bytes minimum)

FieldSizePurpose and notes
Version4 bitsAlways 4 for IPv4.
IHL (Internet Header Length)4 bitsHeader length in 32-bit words. Min = 5 (20 bytes); max = 15 (60 bytes with options).
DSCP6 bitsDifferentiated Services Code Point — QoS marking (e.g. EF for VoIP). Formerly "Type of Service."
ECN2 bitsExplicit Congestion Notification — routers mark this to signal congestion without dropping packets.
Total Length16 bitsEntire packet (header + data) in bytes. Max = 65,535. Minimum = 20 (header only).
Identification16 bitsIdentifies a group of fragments belonging to the same original packet.
Flags3 bitsBit 0: reserved (0). Bit 1: DF (Don't Fragment) — if set and packet too large, router sends ICMP error. Bit 2: MF (More Fragments) — set on all fragments except the last.
Fragment Offset13 bitsPosition of this fragment's data in the original packet, in units of 8 bytes. Max offset = 65,528 bytes.
TTL (Time To Live)8 bitsDecremented by each router. Dropped at 0 → ICMP Time Exceeded sent to source. Default 64 (Linux/macOS), 128 (Windows).
Protocol8 bitsUpper-layer protocol: 1=ICMP, 6=TCP, 17=UDP, 41=IPv6-in-IPv4, 47=GRE, 50=ESP (IPsec), 89=OSPF.
Header Checksum16 bitsOne's complement checksum over the header only (not data). Recalculated at every hop because TTL changes.
Source Address32 bitsSender's IPv4 address. Not authenticated — can be spoofed.
Destination Address32 bitsRecipient's IPv4 address.
Options (optional)0–40 bytesRecord Route, Timestamp, Strict/Loose Source Routing. Rarely used; many routers ignore or strip them.

Worked example: IPv4 packet fragmentation

Every physical link layer enforces a Maximum Transmission Unit (MTU) — the largest IP packet size that the link can carry without splitting (e.g. 1,500 bytes for standard Ethernet). When an IPv4 router receives a datagram larger than the next-hop link's MTU, and the DF (Don't Fragment) bit is 0, it fragments the packet into multiple smaller IPv4 datagrams.

Key rules of IPv4 fragmentation:

  • Every fragment receives its own independent 20-byte IPv4 header copy, retaining the original datagram's 16-bit Identification number.
  • The More Fragments (MF) flag is set to 1 on all fragments except the final fragment (which has MF = 0).
  • Because the 13-bit Fragment Offset field is measured in units of 8-byte blocks (64 bits), the data payload size of every fragment (except the last one) must be an exact multiple of 8 bytes.
  • Fragments are reassembled only at the final destination host, never at intermediate routers (different fragments might take different paths). If even a single fragment is lost in transit, the destination host's reassembly timer expires, the entire original datagram is discarded, and upper-layer protocols (like TCP) must retransmit.
Worked fragmentation calculation:
Original datagram : Total Length = 4,000 bytes (20 B IPv4 header + 3,980 B payload), ID = 777, DF = 0
Outgoing link MTU : 1,500 bytes

Step 1: Compute maximum payload per fragment:
  Max fragment payload = MTU − Header Length = 1,500 − 20 = 1,480 bytes
  Verify 8-byte alignment: 1,480 ÷ 8 = 185 (exact multiple of 8, valid!)

Step 2: Partition payload across fragments:
  • Fragment 1: Carries payload bytes 0–1,479 (1,480 bytes)
    - Total Length    = 1,500 bytes (20 B header + 1,480 B data)
    - Identification  = 777
    - Flags           = MF = 1 (more fragments follow), DF = 0
    - Fragment Offset = 0 ÷ 8 = 0

  • Fragment 2: Carries payload bytes 1,480–2,959 (1,480 bytes)
    - Total Length    = 1,500 bytes (20 B header + 1,480 B data)
    - Identification  = 777
    - Flags           = MF = 1 (more fragments follow), DF = 0
    - Fragment Offset = 1,480 ÷ 8 = 185

  • Fragment 3: Carries remaining payload bytes 2,960–3,979 (1,020 bytes)
    - Total Length    = 1,040 bytes (20 B header + 1,020 B data)
    - Identification  = 777
    - Flags           = MF = 0 (last fragment!), DF = 0
    - Fragment Offset = 2,960 ÷ 8 = 370

IPv4 address space

IPv4 uses 32-bit addresses written as four dot-separated decimal octets: 192.168.10.50. The total space is 2³² = 4,294,967,296 addresses. Excluding reserved ranges, roughly 3.7 billion are theoretically usable as public addresses — far fewer than the world's devices, which is why NAT and IPv6 exist.

Special address ranges

RangePurposeReference
0.0.0.0/8"This network" — used as source before IP is assigned (DHCP Discover)RFC 1122
10.0.0.0/8Private (Class A) — 16.7M addressesRFC 1918
100.64.0.0/10Shared address space (ISP carrier-grade NAT)RFC 6598
127.0.0.0/8Loopback — 127.0.0.1 always refers to "this host"RFC 1122
169.254.0.0/16Link-local (APIPA) — auto-assigned when DHCP failsRFC 3927
172.16.0.0/12Private (Class B range) — 1.05M addressesRFC 1918
192.168.0.0/16Private (Class C range) — 65,536 addressesRFC 1918
224.0.0.0/4Multicast (Class D) — e.g. 224.0.0.5 = all OSPF routersRFC 5771
255.255.255.255/32Limited broadcast (received by all hosts on local segment)RFC 919

Nice-to-know: Historical classful IPv4 addressing

Prior to the introduction of CIDR in 1993 (RFC 1519 / RFC 4632), IPv4 addresses were divided into fixed classes determined by their leading binary bits:

  • Class A (0xxxxxxx, 0.0.0.0–127.255.255.255): Default mask /8 (255.0.0.0). 128 network blocks accommodating ~16.7M hosts (16,777,214 usable addresses) per network. Allocated to massive organisations and early research networks.
  • Class B (10xxxxxx, 128.0.0.0–191.255.255.255): Default mask /16 (255.255.0.0). 16,384 network blocks accommodating 65,534 hosts per network. Allocated to universities and large enterprises.
  • Class C (110xxxxx, 192.0.0.0–223.255.255.255): Default mask /24 (255.255.255.0). Over 2 million network blocks accommodating 254 hosts per network. Assigned to small organisations.
  • Class D (1110xxxx, 224.0.0.0–239.255.255.255): Reserved for multicast groups.
  • Class E (1111xxxx, 240.0.0.0–255.255.255.255): Reserved for experimental use.

Why CIDR replaced classful addressing: Fixed classes caused massive address exhaustion. An organisation requiring 500 IP addresses was too large for a Class C (254 hosts), forcing registries to assign a full Class B (65,534 hosts). The organisation used 500 addresses while wasting over 99% of the block. CIDR eliminated these rigid boundaries by permitting arbitrary prefix lengths (/1 through /32).

CIDR and subnetting — worked examples

CIDR (Classless Inter-Domain Routing, RFC 4632) replaced classful addressing in 1993. An address + prefix length fully defines a subnet. The prefix length is the number of network bits; the remaining bits are host bits.

Binary breakdown example: 192.168.10.100/26

IP address : 192.168.10.100
Binary     : 11000000.10101000.00001010.01100100
Prefix /26 : 11111111.11111111.11111111.11000000  ← subnet mask
             ←────────── 26 network bits ──────→ ←─6 host bits─→

The last octet of the address: 01100100
                                ↑↑
                                These first 2 bits belong to the NETWORK portion.
                                The remaining 6 bits (100100) are HOST bits.

Network bits: 26  →  host bits: 6  →  2^6 = 64 total addresses
Network addr: 11000000.10101000.00001010.01000000 = 192.168.10.64
              (host bits all zeroed)
Broadcast   : 11000000.10101000.00001010.01111111 = 192.168.10.127
              (host bits all ones)
Subnet mask : 255.255.255.192
Wildcard    : 0.0.0.63
First host  : 192.168.10.65
Last host   : 192.168.10.126
Usable hosts: 62  (64 total − 1 network addr − 1 broadcast)

Splitting a /24 into four equal subnets

Start: 10.1.1.0/24  (256 addresses, 254 usable)
Add 2 bits → /26 (4 subnets of 64 addresses each, 62 usable)

Subnet 1:  10.1.1.0/26    hosts: 10.1.1.1  – 10.1.1.62   bcast: 10.1.1.63
Subnet 2:  10.1.1.64/26   hosts: 10.1.1.65 – 10.1.1.126  bcast: 10.1.1.127
Subnet 3:  10.1.1.128/26  hosts: 10.1.1.129– 10.1.1.190  bcast: 10.1.1.191
Subnet 4:  10.1.1.192/26  hosts: 10.1.1.193– 10.1.1.254  bcast: 10.1.1.255

Interactive subnet calculator

Subnet calculator — IPv4 + CIDR


            

VLSM — Variable Length Subnet Masking

Traditional fixed-length subnetting (FLSM) divides a network into subnets of identical size. If a company has four departments requiring 120, 50, 25, and 2 hosts respectively, FLSM forces the administrator to assign a /25 (128 addresses) to every segment — squandering 126 addresses on point-to-point links. VLSM allows an administrator to subnet already-subnetted blocks, applying different mask lengths to fit the exact host requirements of each network segment.

The Golden Rule of VLSM

Always sort and allocate subnets in descending order of size (largest host count first, smallest last). This guarantees that every subnet aligns with a natural power-of-two binary boundary and prevents fragmentation of the remaining unallocated address space.

Worked VLSM design example: Starting with base network 192.168.100.0/24 (256 addresses total), allocate subnets for five distinct requirements:

Subnet nameRequired hostsFormula (2^h − 2 ≥ req)Host bits (h)Prefix (/n)Subnet network addressUsable host rangeBroadcast address
Engineering LAN60 hosts2^6 − 2 = 62 ≥ 606/26 (mask .192)192.168.100.0/26192.168.100.1 – 192.168.100.62192.168.100.63
Sales LAN28 hosts2^5 − 2 = 30 ≥ 285/27 (mask .224)192.168.100.64/27192.168.100.65 – 192.168.100.94192.168.100.95
Management LAN12 hosts2^4 − 2 = 14 ≥ 124/28 (mask .240)192.168.100.96/28192.168.100.97 – 192.168.100.110192.168.100.111
WAN Link 1 (R1–R2)2 hosts2^2 − 2 = 2 ≥ 22/30 (mask .252)192.168.100.112/30192.168.100.113 – 192.168.100.114192.168.100.115
WAN Link 2 (R2–R3)2 hosts2^2 − 2 = 2 ≥ 22/30 (mask .252)192.168.100.116/30192.168.100.117 – 192.168.100.118192.168.100.119

Notice that addresses 192.168.100.120 through 192.168.100.255 (136 addresses, including a contiguous /25 block at 192.168.100.128/25) remain completely free for future expansion.

Route aggregation (supernetting)

Route aggregation (also called supernetting or prefix summarization) is the ability of CIDR to consolidate multiple contiguous, smaller address blocks into a single summary prefix. In core internet routers, routing tables would otherwise grow uncontrollably with hundreds of thousands of individual customer routes. By advertising a single aggregated prefix via BGP, ISPs dramatically reduce router memory consumption and routing protocol churn.

Worked aggregation example: Suppose an ISP allocates four contiguous /24 customer subnets:

  • Customer 1: 203.0.112.0/24 → 3rd octet in binary: 01110000
  • Customer 2: 203.0.113.0/24 → 3rd octet in binary: 01110001
  • Customer 3: 203.0.114.0/24 → 3rd octet in binary: 01110010
  • Customer 4: 203.0.115.0/24 → 3rd octet in binary: 01110011

Comparing the bits of the 3rd octet, all four networks share the exact same first 6 bits: 011100. Combining the two initial octets (16 bits) with these 6 matching bits yields 22 network bits:

Aggregated Supernet Route = 203.0.112.0/22  (mask 255.255.252.0)

Instead of advertising four separate routes to external BGP peers, the ISP advertises a single route for 203.0.112.0/22 covering all 1,024 IP addresses (from 203.0.112.0 to 203.0.115.255).

Longest prefix match with exceptions: What happens if Customer 3 (203.0.114.0/24) changes internet providers and moves to a competing ISP B? ISP B begins advertising the more specific route 203.0.114.0/24 to the global internet, while ISP A continues advertising its broad aggregate 203.0.112.0/22. Global routers applying the Longest Prefix Match (LPM) rule compare the prefix lengths: because /24 is longer and more specific than /22, packets destined for 203.0.114.x are automatically routed to ISP B, while all packets for .112.x, .113.x, and .115.x continue flowing to ISP A without issue.

IPv6 — Internet Protocol version 6 (RFC 8200)

IPv4 address exhaustion was anticipated in the early 1990s. IPv6, finalised in 1998, uses 128-bit addresses — providing 2¹²⁸ ≈ 3.4 × 10³⁸ addresses, enough for every atom on Earth's surface to have its own address, with many orders of magnitude to spare.

IPv6 address notation

Written as eight groups of four hex digits, colon-separated: 2001:0db8:85a3:0000:0000:8a2e:0370:7334. Simplification rules:

  • Leading zeros in each group can be omitted: 2001:db8:85a3:0:0:8a2e:370:7334
  • One consecutive run of all-zero groups can be replaced with ::: 2001:db8:85a3::8a2e:370:7334
  • Loopback: ::1 (equivalent to 127.0.0.1)
  • Unspecified: :: (equivalent to 0.0.0.0)

IPv6 address types

TypePrefixDescription
Global Unicast2000::/3Publicly routable; analogous to public IPv4. IANA allocates global unicast blocks out of the 2000::/3 range (addresses starting with binary 001, such as 2001::/16 through 2c00::/12).
Link-local Unicastfe80::/10Auto-configured on every IPv6 interface; not routable; required for neighbour discovery. Analogous to 169.254.0.0/16.
Unique Localfc00::/7Private, not routable on the internet; analogous to RFC 1918. Random 40-bit global ID makes collisions unlikely during mergers.
Multicastff00::/8Replaces IPv4 broadcast. ff02::1 = all nodes, ff02::2 = all routers, ff02::5/6 = OSPFv3.
Loopback::1/128This host.

Key IPv6 improvements over IPv4

  • No header checksum: recalculating per-hop was expensive; offloaded to transport and link layers.
  • No router fragmentation: routers never fragment packets. Sources must use PMTUD (minimum guaranteed MTU on any IPv6 link is 1280 bytes). This simplifies and speeds up forwarding.
  • SLAAC (Stateless Address Autoconfiguration, RFC 4862): a host derives its own global address from the router's advertised prefix + its interface identifier (derived from MAC or randomly generated via RFC 7217 privacy extensions). No DHCP required, though DHCPv6 also exists.
  • Neighbour Discovery Protocol (NDP, RFC 4861): replaces ARP using ICMPv6. More secure, extensible, and multicast-based (no broadcasts).
  • IPsec support: originally mandated (now "should" implement per RFC 6434), but authentication headers work the same way.

Routing — how packets find their way

Every IP-speaking device (hosts, routers) has a routing table mapping destination prefixes to next-hop addresses or outgoing interfaces. When a packet arrives, the device applies the longest prefix match rule — the entry with the most specific (longest) matching prefix wins.

# Linux routing table
$ ip route show
default via 10.0.0.1 dev eth0                   ← 0.0.0.0/0 (prefix length 0)
10.0.0.0/8 dev eth0 proto kernel scope link     ← directly connected
10.0.0.128/25 via 10.0.0.250 dev eth0           ← more specific, wins for /25
192.168.100.0/24 via 10.0.0.1 dev eth0

# Example decision for packet to 10.0.0.150:
# Matches: 10.0.0.0/8 (prefix 8) AND 10.0.0.128/25 (prefix 25)
# Longest match wins → forward via 10.0.0.128/25 route (next hop: 10.0.0.250)

Static vs. dynamic routing

Static routes are manually configured by an administrator. Advantages: predictable, no routing overhead, no chance of a protocol bug sending traffic the wrong way. Disadvantages: doesn't adapt to failures; doesn't scale to the internet's size.

Dynamic routing protocols Nice-to-know — Details in Computer Networking II let routers automatically discover topology and compute paths:

ProtocolTypeAlgorithmScopeRFC
RIPDistance vectorBellman-Ford; metric = hop count (max 15)Small networks; largely obsoleteRFC 2453
OSPFLink-stateEach router knows full topology; Dijkstra's algorithm; metric = cost (bandwidth-based)Intra-AS (single organisation)RFC 2328
IS-ISLink-stateSimilar to OSPF; preferred by large ISPs (runs directly over layer 2, not IP)Intra-AS, large providersISO 10589
EIGRPAdvanced distance vectorDUAL algorithm; composite metric; Cisco proprietary (now open)Intra-AS, Cisco environmentsRFC 7868
BGP-4Path vectorExchanged AS_PATH prevents loops; policy-driven; TCP port 179Inter-AS (between ISPs and organisations)RFC 4271

Autonomous System (AS): a network under one administrative control, identified by a 16- or 32-bit ASN (Autonomous System Number). Example: AS13335 = Cloudflare, AS15169 = Google. BGP exchanges reachability information between ASes.

Static routing worked example: Three routers end-to-end

To understand how routers forward packets hop-by-hop without dynamic protocols, consider a network connecting two offices across three intermediate routers:

Host A .10.5 LAN A: .10.0/24 Router R1 eth0:.10.1 eth1:.12.1 WAN1: 10.1.2.0/30 Router R2 eth0:.12.2 eth1:.23.1 WAN2: 10.2.3.0/30 Router R3 eth0:.23.2 eth1:.20.1 LAN B: .20.0/24 Host B .20.50
Three-router static network connecting Host A (192.168.10.5) to Host B (192.168.20.50).

For communication to succeed between Host A and Host B, the administrator must configure explicit static routes in all three routing tables:

RouterDestination networkNext-hop IPOutgoing interfaceType & role
R1192.168.10.0/24— (Direct)eth0Connected: Local LAN A
10.1.2.0/30— (Direct)eth1Connected: Link to R2
192.168.20.0/2410.1.2.2eth1Static: Reach LAN B via R2
R2 (Transit)10.1.2.0/30— (Direct)eth0Connected: Link to R1
10.2.3.0/30— (Direct)eth1Connected: Link to R3
192.168.10.0/2410.1.2.1eth0Static: Reach LAN A via R1
192.168.20.0/2410.2.3.2eth1Static: Reach LAN B via R3
R3192.168.20.0/24— (Direct)eth1Connected: Local LAN B
10.2.3.0/30— (Direct)eth0Connected: Link to R2
192.168.10.0/2410.2.3.1eth0Static: Reach LAN A via R2

Hop-by-hop packet forwarding walkthrough (Host A → Host B):

  1. Host A (192.168.10.5) checks destination 192.168.20.50. Mask comparison shows it is outside LAN A. Host A looks up its default gateway (192.168.10.1), sends an ARP request for R1's MAC, and transmits an Ethernet frame with dst MAC = R1.
  2. Router R1 receives the frame on eth0, strips the Ethernet header, decrements IPv4 TTL by 1. R1 looks up 192.168.20.50 in its FIB → matches 192.168.20.0/24 with next-hop 10.1.2.2. R1 encapsulates the packet in a new Ethernet frame (src MAC = R1 eth1, dst MAC = R2 eth0) and transmits across WAN1.
  3. Router R2 receives on eth0, decrements TTL. R2 consults its FIB → matches 192.168.20.0/24 with next-hop 10.2.3.2 on eth1. R2 rewrites link-layer MACs and forwards across WAN2.
  4. Router R3 receives on eth0, decrements TTL. R3 matches destination 192.168.20.50 to directly connected network on eth1. R3 ARPs for Host B, encapsulates into a frame, and delivers directly to Host B.

Crucial lesson on asymmetric routing: Network routing is one-way! If the administrator configures routes from R1 → R2 → R3, Host A's packets reach Host B. But if R2 lacks a return route for 192.168.10.0/24, Host B's replies will be silently dropped at R2, resulting in 100% packet loss on ping. Every intermediate hop must have both forward and reverse paths defined.

ICMP — Internet Control Message Protocol (RFC 792)

ICMP carries error messages and diagnostic information within the IP layer. It is encapsulated in IP packets (Protocol = 1). ICMP is not a transport protocol — it carries no user data. Key message types:

TypeCodeMeaningTriggered by
00Echo ReplyResponse to ping
30Dest Unreachable: Network UnreachableNo route to destination network
31Dest Unreachable: Host UnreachableHost down or no ARP reply
33Dest Unreachable: Port UnreachableUDP sent to closed port
34Dest Unreachable: Fragmentation NeededDF bit set but packet too large; includes next-hop MTU
80Echo Requestping command
110Time Exceeded: TTL expired in transitTTL decremented to 0; used by traceroute
120Parameter ProblemMalformed IP header field

How traceroute works

traceroute sends a series of packets with TTL = 1, 2, 3, … Each router decrements TTL; when it reaches 0, the router drops the packet and sends back ICMP Type 11 (Time Exceeded) to the source, revealing its IP and RTT. On Linux/macOS, traceroute uses UDP by default (ports 33434+); on Windows, tracert uses ICMP Echo Requests. Many networks block ICMP, explaining * * * output for some hops.

NAT / PAT — in detail

NAT (Network Address Translation, RFC 3022) modifies IP addresses in packet headers as they pass through a router. The most common form today is NAPT / PAT (Port Address Translation), often loosely called "NAT overload."

The NAT router maintains a translation table:

# NAT translation table (conceptual)
Internal src          External src (after NAT)   Destination           Proto
192.168.1.10:54321    203.0.113.1:40001           93.184.216.34:443     TCP
192.168.1.20:54890    203.0.113.1:40002           93.184.216.34:443     TCP
192.168.1.10:54322    203.0.113.1:40003           8.8.8.8:53            UDP

# Outbound: src IP/port rewritten to public IP + new port
# Inbound: dst IP/port rewritten back to original private IP/port

NAT implications and problems:

  • Breaks end-to-end connectivity: external hosts cannot initiate connections to internal hosts — they don't know the private IP or port. Peer-to-peer applications (BitTorrent, WebRTC, gaming) need NAT traversal techniques (STUN, TURN, ICE, UPnP, NAT-PMP).
  • Complicates protocols: protocols that embed IP addresses in payload (FTP, SIP, H.323) need application-layer gateways (ALGs) to rewrite those embedded addresses.
  • Carrier-Grade NAT (CGN/CGNAT): ISPs deploy NAT at their own network, putting entire customer networks behind a shared public IP. RFC 6598 reserves 100.64.0.0/10 for this.
  • IPv6 solution: every device gets a globally routable IPv6 address; NAT is not needed and is generally avoided.

Port forwarding (DNAT — Destination NAT)

Standard NAT/PAT handles outbound traffic (Source NAT / SNAT), mapping multiple private LAN addresses to a single public IP. However, because external internet hosts have no route to private RFC 1918 addresses, they cannot initiate inbound connections to internal devices. Port forwarding (DNAT — Destination Network Address Translation) solves this by rewriting destination IP addresses and ports on inbound packets.

When an incoming packet arrives at the router's external WAN interface, the router consults its static DNAT rules:

External interface & portInternal destination IP & portService description
198.51.100.1:80 (WAN)192.168.1.50:80 (LAN)Internal HTTP web server
198.51.100.1:2222 (WAN)192.168.1.10:22 (LAN)Internal SSH server (port-translated)
198.51.100.1:25565 (WAN)192.168.1.75:25565 (LAN)Minecraft game server
# Linux DNAT rule using iptables (PREROUTING chain):
$ sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.50:80

# Equivalent rule in modern nftables:
$ sudo nft add rule ip nat PREROUTING iif "eth0" tcp dport 8080 dnat to 192.168.1.50:80

Hairpin NAT (NAT loopback): A common problem arises when a device inside the LAN attempts to access the forwarded server using its public domain name or WAN IP. Without hairpinning, the router sends the packet to the server, but the server replies directly to the client's private IP, bypassing the router; the client drops the reply because it expected a response from the public IP. Hairpin NAT applies both DNAT and SNAT to internal requests directed at the public interface, keeping the connection symmetric.

Network tunneling and encapsulation

Tunneling encapsulates packets of one network protocol inside the payload of another (or the same) protocol. This creates an overlay network, allowing private or foreign packets to traverse an intermediate transit network without intermediate routers needing to understand or route the inner addresses.

Common tunneling protocols

  • IP-in-IP (RFC 2003): Protocol number 4. Simplest encapsulation: prepends an outer 20-byte IPv4 header to an inner IPv4 packet. No encryption; often used in mobile IP and internal cluster routing.
  • GRE (Generic Routing Encapsulation, RFC 2784): Protocol number 47. Cisco-developed, standardised protocol capable of encapsulating arbitrary layer-3 payloads (including multicast and IPv6) over IPv4 backbones. Adds 4 to 16 bytes of header overhead.
  • WireGuard & IPsec: Encrypted tunnels. IPsec uses ESP (Encapsulating Security Payload, protocol 50); WireGuard encapsulates ChaCha20-Poly1305 encrypted packets within standard UDP datagrams (port 51820).
  • VXLAN (RFC 7348) Overlay — Not on exam: Encapsulates entire Layer-2 Ethernet frames inside Layer-4 UDP packets (port 4789). Extends VLAN boundaries from 4,096 to over 16 million Virtual Network Identifiers (VNIs) across cloud data-centre spine-leaf fabrics.

Textbook walkthrough: IPv6-in-IPv4 Tunneling (RFC 4213, Protocol = 41)

The transition from IPv4 to IPv6 relies heavily on tunneling to connect isolated IPv6 networks across legacy IPv4-only internet infrastructure. Consider two IPv6 networks connected via dual-stack border routers (Router B and Router E) separated by IPv4-only transit routers (Router C and Router D):

[IPv6 Node] → (IPv6) → [Router B] === (IPv4 transit: Router C → Router D) ===> [Router E] → (IPv6) → [IPv6 Node]
                      (Ingress)                                               (Egress)
  1. Encapsulation at ingress border router (Router B):
    An IPv6 host on the left sends an IPv6 datagram: Src IP = 2001:db8:1::10, Dst IP = 2001:db8:2::50.
    Router B determines the path must cross the IPv4 core. It treats the entire 40-byte IPv6 datagram as payload and encapsulates it inside a newly generated outer IPv4 header:
    • Outer IPv4 header: Src IP = 198.51.100.1, Dst IP = 203.0.113.9, Protocol = 41 (IPv6 encapsulation).
    • IPv4 payload: The complete, unmodified inner IPv6 datagram.
  2. Transit through IPv4 core (Routers C & D):
    Intermediate routers C and D are pure IPv4 routers. They inspect solely the outer IPv4 destination (203.0.113.9) and forward the packet using standard IPv4 routing tables, completely unaware that the payload contains an IPv6 packet.
  3. Decapsulation at egress border router (Router E):
    Router E (203.0.113.9) receives the packet, reads Protocol = 41, strips the 20-byte outer IPv4 header, and extracts the inner IPv6 datagram. Router E then routes the restored IPv6 packet natively onto its local IPv6 LAN to destination 2001:db8:2::50.

The MTU and MSS clamping challenge in tunnels

Every tunnel adds encapsulation headers, which subtracts from the maximum payload size the physical link can carry. On a standard 1,500-byte Ethernet connection, an IPsec ESP or WireGuard tunnel adds approximately 52 to 80 bytes of overhead, dropping the effective Path MTU to 1,420–1,448 bytes. If a client transmits a 1,500-byte packet with the DF (Don't Fragment) bit set and intermediate firewalls block ICMP Fragmentation Needed messages, packets vanish into an MTU black hole. Routers resolve this using MSS Clamping: the router rewrites the TCP MSS option in passing SYN packets to a safe value (e.g. 1,380 bytes), forcing both endpoints to size their TCP segments to fit the tunnel without fragmentation.

Router internals: Architecture and packet scheduling

A router operates at two radically different time scales, strictly separating its architecture into the Control Plane and the Data Plane (Forwarding Plane):

DimensionControl PlaneData Plane (Forwarding Plane)
Primary functionRuns routing protocols (BGP, OSPF); computes topology and builds the Routing Information Base (RIB).Examines incoming packet headers, consults Forwarding Information Base (FIB), moves bits from input port to output port.
ImplementationSoftware running on general-purpose CPU.Dedicated hardware: ASICs, Network Processors, and TCAM.
Time scaleMilliseconds to seconds (slow path).Nanoseconds to microseconds (fast path, line rate).

Internal router components

  1. Input ports: Terminate physical links, decapsulate link-layer frames, and perform line-rate destination IP lookups in the FIB using TCAM (Ternary Content Addressable Memory). TCAM evaluates all prefix rules in parallel in a single clock cycle, enabling constant-time O(1) longest prefix matching.
    Input-Queue Head-of-Line (HOL) Blocking: Even if a router employs an ideal non-blocking crossbar fabric, contention can still occur if two packets at the front of two distinct input queues are destined for the same output port simultaneously. One packet must wait. That waiting packet stalls all packets queued behind it in the same input FIFO buffer — even if those queued packets are destined for completely idle, conflict-free output ports! Under uniform random traffic, FIFO input queuing mathematically caps total switch throughput to at most 2 − √2 ≈ 58.6%. Modern routers eliminate this bottleneck using Virtual Output Queuing (VOQ), maintaining a separate queue at each input port for every destination output port.
  2. Switching fabric: The high-speed interconnect linking input ports to output ports:
    • Memory: CPU copies packets between ports via system RAM (early routers; throughput capped by bus memory bandwidth).
    • Shared bus: Ports communicate over a shared internal bus; only one packet can transfer at a time.
    • Crossbar switch: A 2D grid of interconnected fabric points allowing multiple non-conflicting packet transfers simultaneously in parallel. Modern high-capacity switches and core routers use multi-stage crossbar fabrics.
  3. Output ports: Buffer packets when the switching fabric delivers data faster than the outgoing line can transmit, and schedule packets onto the physical wire.

Packet scheduling algorithms

When an output buffer experiences congestion, the packet scheduler determines the transmission order of queued packets:

  • FIFO (First-In, First-Out): Delivers packets strictly in arrival order. Zero QoS differentiation; interactive VoIP packets wait behind bulk file downloads.
  • Priority Queuing (PQ): Partitions traffic into priority queues (e.g. High, Medium, Low). Highest priority queue is always emptied first. Limitation: Lower priority flows can suffer complete starvation.
  • Round Robin (RR): Scans active classes cyclically, dispatching one packet from each. Prevents starvation, but unfair if one class sends 1,500-byte packets and another sends 64-byte packets.
  • Weighted Fair Queuing (WFQ): Generalised Processor Sharing. Each traffic flow receives a configurable percentage of link bandwidth. The scheduler computes a virtual completion time for each packet based on its byte length, interleaving transmissions to guarantee bit-level fairness regardless of individual packet sizes.

Buffer management: Drop Tail vs. AQM: When a FIFO queue fills completely, default Drop Tail discards all incoming packets. This leads to TCP global synchronisation: hundreds of flows simultaneously experience packet loss, drop their congestion windows at the exact same instant, and recover in unison, causing severe bandwidth oscillations. Modern routers use Active Queue Management (AQM) like RED (Random Early Detection) and CoDel (Controlled Delay) to drop or ECN-mark packets probabilistically before the buffer is exhausted, smoothing throughput and combating bufferbloat.

Extra Knowledge: SDN, Generalized Forwarding, and Middleboxes Beyond

Modern network architectures increasingly move beyond traditional per-router routing algorithms and simple destination-based forwarding toward programmable flow tables and specialised intermediate processing appliances.

Generalized Forwarding (Match-Plus-Action)

Traditional routers perform destination-based forwarding: when a packet arrives, the router inspects only the destination IP address, searches its Forwarding Information Base (FIB) using Longest Prefix Match, and transmits the datagram out of a specific interface.

By contrast, generalized forwarding (popularised by OpenFlow and P4) models network elements as flexible match-plus-action engines. Instead of looking only at the destination IP, an OpenFlow switch evaluates an arbitrary set of header fields across multiple protocol layers simultaneously:

  • Layer 2: Source and Destination MAC addresses, Ethernet type, VLAN ID / priority.
  • Layer 3: Source and Destination IPv4/IPv6 addresses, protocol field, ToS / DSCP bits.
  • Layer 4: Source and Destination TCP/UDP port numbers, TCP flags.

When an incoming datagram matches a flow table rule, the switch executes one or more specified actions:

  • Forward: Direct the datagram to one or more egress ports (supporting point-to-point forwarding or multicast fan-out).
  • Drop: Silently discard the packet, implementing line-rate firewall and ACL filtering.
  • Modify: Rewrite header values (e.g. rewriting IP addresses and port numbers for NAT, decrementing TTL, or pushing/popping VLAN tags).
  • Send to Controller: Encapsulate and forward the unrecognised packet to the centralised SDN controller for policy decisions.

Software-Defined Networking (SDN)

Traditional computer networking relies on a distributed control plane: each router independently runs routing daemons (such as OSPF, IS-IS, or BGP) in its own operating system, exchanges routing state with neighbours, computes shortest paths, and populates its local forwarding table.

Software-Defined Networking (SDN) decouples the network into two distinct, specialised tiers:

  • Logically Centralised Control Plane: The routing and control logic is removed from individual routers and consolidated into an SDN Controller (or a resilient distributed controller cluster like ONOS or OpenDaylight). The controller maintains a complete, centralised view of network topology, link loads, and access policies, calculating flow paths as software applications.
  • Data Plane (Forwarding Plane): Simple, high-speed hardware switches ("white-box" switches) equipped with TCAM flow tables that execute fast match-action packet processing without running distributed routing algorithms.
  • Southbound API: A standardised protocol interface (such as OpenFlow or P4Runtime) through which the SDN controller communicates with data-plane switches to install, update, and monitor flow table rules.

Middleboxes and the End-to-End Principle

RFC 3234 defines a middlebox as "any intermediate device on the datagram path between a source host and destination host that performs functions other than the normal, standard functions of an IP router on the datagram path". While traditional routers merely examine IP headers to forward datagrams hop-by-hop, middleboxes inspect, modify, filter, or terminate traffic:

  • NATboxes (Network Address Translation): Rewrite private RFC 1918 addresses and ephemeral port numbers to public routable IPs and ports, overcoming IPv4 exhaustion.
  • Firewalls & IDS/IPS: Enforce security policies via stateless packet filtering (IP/port matching), stateful inspection (tracking TCP handshake state and sequence numbers), or Deep Packet Inspection (DPI, scanning application payloads for exploits).
  • Load Balancers: Distribute client workloads across back-end server pools using Layer 4 transport load balancing (DNAT/IP tunneling) or Layer 7 reverse proxying (HTTP URL path routing, TLS termination).
  • Web Caches, Proxies & WAN Optimisers: Store cached HTTP objects, terminate and split TCP connections across high-latency WAN links, and enforce MSS clamping to prevent tunnel fragmentation.

Trade-offs and Protocol Ossification: Although middleboxes deliver critical performance and security capabilities, they violate the fundamental end-to-end principle of the Internet architecture (which states that network reliability and intelligence should reside exclusively at communicating end hosts, with the network core remaining a simple, stateless packet carrier). Furthermore, middleboxes frequently drop packets bearing unfamiliar TCP options or experimental protocol numbers, creating severe protocol ossification. This rigid ossification was the primary catalyst for modern protocols like QUIC (RFC 9000), which encrypts transport-layer headers inside standard UDP datagrams to prevent on-path middleboxes from meddling with transport state.

Key takeaways

  • IPv4 header: minimum 20 bytes; TTL prevents loops; DF bit controls fragmentation.
  • RFC 1918 private ranges: 10/8, 172.16/12, 192.168/16 — not routable on the public internet.
  • CIDR: prefix length = network bits; 2^(32-prefix) = total addresses; subtract 2 for usable hosts.
  • Longest prefix match: most specific route wins (e.g. /25 beats /8 beats /0).
  • OSPF = intra-organisation link-state; BGP = inter-AS path vector for the internet.
  • ICMP Type 8 = Echo Request (ping); Type 11 = TTL exceeded (traceroute).
  • NAT/PAT allows many private addresses to share one public IP via port rewriting.
  • IPv6 uses 128-bit addresses, eliminates NAT, forbids router fragmentation, and replaces ARP with NDP.
  • DNAT (Port Forwarding) rewrites incoming destination IP/port to internal hosts; tunneling encapsulates packets in outer headers (requires MSS clamping to avoid MTU black holes). Routers separate control plane (software RIB) from data plane (hardware TCAM FIB); WFQ and AQM (CoDel/RED) prevent starvation and bufferbloat.
  • VLSM sorts subnets in descending host requirement order to prevent address fragmentation. Static routing requires explicit forward AND return routes on every intermediate hop.

Quick check — Chapter 3

1. How many usable host addresses are in the subnet 10.0.0.0/29?

/29 → 3 host bits → 2³ = 8 total addresses. Subtract network (10.0.0.0) and broadcast (10.0.0.7) = 6 usable hosts (10.0.0.1–10.0.0.6).

2. What happens when a router receives an IPv4 packet with TTL = 1?

The router decrements TTL from 1 to 0, drops the packet, and sends ICMP Time Exceeded (Type 11, Code 0) back to the source. traceroute exploits this by incrementing TTL to discover each hop.

3. How does IPv6 differ from IPv4 regarding packet fragmentation and link-layer address resolution?

In IPv6, intermediate routers never fragment packets; if a packet exceeds the next-hop MTU, the router drops it and returns an ICMPv6 Packet Too Big message. Additionally, IPv6 eliminates the hop-by-hop header checksum and replaces IPv4's broadcast ARP with multicast-based Neighbour Discovery Protocol (NDP).

4. Two packets both match routing table entries: 10.0.0.0/8 and 10.1.2.0/24. The destination is 10.1.2.50. Which entry is used?

Longest prefix match: /24 (24 network bits) is more specific than /8 (8 network bits), so 10.1.2.0/24 wins. This rule allows both a specific route and a catch-all to coexist in the same table.

5. Which packet scheduling algorithm guarantees proportional bandwidth sharing among different traffic classes while actively compensating for differences in packet lengths?

Weighted Fair Queuing (WFQ) assigns weights to queues and schedules packets based on their bit-length virtual transmission times. This prevents starvation and ensures bandwidth allocation is proportional to configured weights regardless of packet size.

6. A WireGuard VPN tunnel runs over an Ethernet connection with an MTU of 1,500 bytes. The tunnel encapsulation adds an outer IPv4 header (20 bytes) and a WireGuard UDP header (32 bytes). For an inner TCP flow over IPv4 (20-byte IP header, 20-byte TCP header), what is the maximum TCP MSS that avoids fragmentation?

Physical MTU is 1,500 bytes. Tunnel overhead = 20 (outer IP) + 32 (WireGuard UDP) = 52 bytes. Effective tunnel MTU = 1,500 − 52 = 1,448 bytes. Inner TCP MSS = tunnel MTU − inner IP (20) − inner TCP (20) = 1,448 − 40 = 1,408 bytes.

7. Using VLSM, an administrator needs to allocate a subnet for a department with 85 host computers. What is the most efficient prefix length that satisfies this requirement?

Formula: 2^h − 2 ≥ 85. For h = 6, 2^6 − 2 = 62 (too small). For h = 7, 2^7 − 2 = 126 ≥ 85. The required prefix length is 32 − 7 = /25, offering 126 usable host addresses.

8. In the three-router static network, Host A (192.168.10.5) pings Host B (192.168.20.50). ICMP Echo Requests arrive at Host B, but Host A receives no replies. Routers R1 and R3 have complete routing tables. Which missing route on transit Router R2 causes this failure?

Routing is strictly directional. If Echo Requests reach Host B, the forward path works. When Host B replies, R3 sends the Echo Reply to R2. If R2 lacks a static route for destination network 192.168.10.0/24 via 10.1.2.1, R2 drops the packet because it has no route back to Host A's subnet.

9. An IPv4 datagram of Total Length = 3,000 bytes (20-byte IPv4 header + 2,980-byte payload) must traverse a link with MTU = 1,500 bytes. What are the Total Length, MF (More Fragments) flag, and Fragment Offset of the SECOND fragment?

Max fragment payload = 1,500 − 20 = 1,480 bytes (a multiple of 8).
• Fragment 1 carries payload bytes 0–1,479 (1,480 B); Offset = 0; MF = 1.
• Fragment 2 carries payload bytes 1,480–2,959 (1,480 B); Total Length = 1,480 + 20 = 1,500; Offset = 1,480 ÷ 8 = 185; MF = 1 (since 20 bytes remain for Fragment 3).
• Fragment 3 carries payload bytes 2,960–2,979 (20 B); Total Length = 40; Offset = 2,960 ÷ 8 = 370; MF = 0.

10. An ISP wishes to aggregate the four contiguous subnets 192.168.8.0/24, 192.168.9.0/24, 192.168.10.0/24, and 192.168.11.0/24 into a single summary route advertisement. What is the correct aggregated CIDR prefix?

Examine the 3rd octets in binary:
• 8 = 00001000
• 9 = 00001001
• 10 = 00001010
• 11 = 00001011
All four share the identical first 6 bits: 000010. Combining the first two octets (16 bits) with these 6 bits yields 16 + 6 = 22 network bits, giving supernet prefix 192.168.8.0/22.