Sub topic 5
Layer 3: Network, IP addressing and routing
This chapter assumes you know the layer names from the earlier chapters and how encapsulation works. It also assumes you can read binary and dotted-decimal numbers and can run commands in a Linux terminal.
Layer 2 moves frames between devices on one link. Layer 3 moves packets between networks that may be many hops apart. It gives each host a logical address, and it makes forwarding decisions based on that address.
What Layer 3 is responsible for
Layer 3 has three jobs:
- Logical addressing. Every interface gets an address that identifies both the network it sits on and the host within that network. Unlike a MAC address, an IP address can be assigned and changed.
- Routing. Each router chooses the next hop for a packet by looking up the destination address in a routing table.
- Best-effort delivery. IP does not guarantee delivery, ordering, or absence of duplicates. Those guarantees, when needed, come from Layer 4.
The Layer 3 data unit is the packet. The Layer 3 header is rebuilt by the sender but is not rewritten by routers, apart from a few fields such as TTL. The Layer 2 frame around it is thrown away and rebuilt at every hop.
The IPv4 header
An IPv4 header is at least 20 bytes. These are the fields you will meet most often.
| Field | Size | Purpose |
|---|---|---|
| Version | 4 bits | 4 for IPv4 |
| IHL | 4 bits | Header length in 32-bit words (5 means 20 bytes) |
| Total length | 16 bits | Header plus payload, in bytes |
| Identification, flags, fragment offset | 16, 3, 13 bits | Reassembly of fragmented packets; the DF flag forbids fragmentation |
| TTL | 8 bits | Hop limit, decremented by each router |
| Protocol | 8 bits | Which Layer 4 protocol follows (1 ICMP, 6 TCP, 17 UDP) |
| Header checksum | 16 bits | Detects corruption in the header only |
| Source and destination address | 32 bits each | The endpoints |
The Protocol field does for Layer 3 what EtherType does for Layer 2. It tells the receiver which upper-layer protocol should get the payload.
The following script parses a sample header using the same struct approach as the Ethernet example:
import struct
import ipaddress
# 20-byte IPv4 header: ICMP packet from 10.0.0.1 to 10.0.0.2, TTL 64, DF set
raw = bytes.fromhex("4500005400004000400100000a0000010a000002")
(vihl, tos, total_len, ident, flags_frag,
ttl, proto, checksum, src, dst) = struct.unpack("!BBHHHBBH4s4s", raw)
print("version:", vihl >> 4)
print("header bytes:", (vihl & 0x0F) * 4)
print("total length:", total_len)
print("TTL:", ttl, "protocol:", proto)
print("DF set:", bool(flags_frag & 0x4000))
print("src:", ipaddress.IPv4Address(src), "dst:", ipaddress.IPv4Address(dst))It prints version 4, a 20-byte header, total length 84, TTL 64, protocol 1 (ICMP), DF set, source 10.0.0.1 and destination 10.0.0.2. The checksum field is zero in this sample, so the script does not verify it.
IPv4 addresses, prefixes, and subnets
An IPv4 address is 32 bits, written as four decimal bytes. A prefix length splits it into a network part and a host part. In 192.168.1.130/26, the first 26 bits identify the network and the last 6 bits identify the host. The same split can be written as a subnet mask: /26 is 255.255.255.192.
This notation is called CIDR (Classless Inter-Domain Routing). It replaced the old class A, B, and C scheme, in which the split was fixed by the first bits of the address. With CIDR, any prefix length from /0 to /32 is valid.
For a prefix with h host bits:
- The block holds 2^h addresses.
- The first address is the network address and the last is the broadcast address. Neither is assigned to a host in a normal subnet.
- The usable host count is 2^h − 2.
Python's ipaddress module does this arithmetic for you:
import ipaddress
iface = ipaddress.ip_interface("192.168.1.130/26")
net = iface.network
print(net) # 192.168.1.128/26
print(net.netmask) # 255.255.255.192
print(net.broadcast_address) # 192.168.1.191
print(net.num_addresses - 2) # 62 usable hosts
# Is another host on the same subnet?
print(ipaddress.ip_address("192.168.1.150") in net) # True
print(ipaddress.ip_address("192.168.1.200") in net) # FalseThat last test is the one every host performs before sending. If the destination is inside its own subnet, the host sends directly, using ARP to find the destination MAC address. If not, it sends the packet to its default gateway, again using ARP to find the gateway's MAC address.
Special and private ranges
| Range | Meaning |
|---|---|
| 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | Private (RFC 1918). Not routed on the public internet. |
| 127.0.0.0/8 | Loopback. Traffic never leaves the host. |
| 169.254.0.0/16 | Link-local. Hosts self-assign this when DHCP fails. |
| 100.64.0.0/10 | Shared address space used by carrier-grade NAT |
| 0.0.0.0/0 | In a routing table, the default route |
An address in 169.254.0.0/16 on a client is a useful diagnostic. It means the interface came up but never received a DHCP lease.
NAT
Private addresses reach the internet through network address translation. A NAT device, usually your home router, rewrites the source address (and usually the source port) of outbound packets to its own public address. It keeps a table so it can reverse the rewrite on replies. NAT is a Layer 3 function that depends on Layer 4 port numbers, which is one reason strict layer boundaries blur in practice.
Routing
A routing table maps destination prefixes to a next hop and an outgoing interface. When a packet arrives, the router finds every entry whose prefix contains the destination address. It then picks the entry with the longest prefix, meaning the most specific match. The /0 default route matches everything, so it is used only when nothing more specific exists.
This script implements the lookup:
import ipaddress
routes = [
("0.0.0.0/0", "192.168.1.1 (default gateway)"),
("192.168.1.0/24", "direct via eth0"),
("10.0.0.0/8", "192.168.1.254"),
("10.20.0.0/16", "192.168.1.253"),
]
table = [(ipaddress.ip_network(p), hop) for p, hop in routes]
def lookup(dest):
addr = ipaddress.ip_address(dest)
matches = [(net, hop) for net, hop in table if addr in net]
net, hop = max(matches, key=lambda m: m[0].prefixlen)
return f"{dest} -> {hop} (matched {net})"
for d in ["10.20.5.9", "10.99.1.1", "192.168.1.50", "8.8.8.8"]:
print(lookup(d))The output shows 10.20.5.9 going to 192.168.1.253 because the /16 beats the /8, 10.99.1.1 going to 192.168.1.254, 192.168.1.50 delivered directly, and 8.8.8.8 falling through to the default gateway.
Routing tables are filled in two ways:
- Static routes are entered by an administrator. They are simple and predictable, but they do not adapt to failures.
- Dynamic routing protocols such as OSPF (inside an organisation) and BGP (between organisations on the internet) exchange reachability information and recompute routes when links fail. These protocols run on top of IP, but their job is to serve Layer 3, so they are usually classed with it.
What happens at each hop
At every router the following steps happen:
- The router accepts a frame addressed to its own MAC address and removes the Layer 2 header.
- It decrements the TTL. If the TTL reaches 0, it drops the packet and sends an ICMP "Time Exceeded" message back to the source.
- It performs the longest-prefix lookup on the destination address.
- It builds a new frame addressed to the next hop's MAC address and sends it.
The TTL prevents packets from circulating forever when a routing loop exists. traceroute exploits it by sending probes with TTL 1, 2, 3, and so on. Each router that discards a probe reveals itself through the ICMP reply.
ICMP, MTU, and fragmentation
ICMP (Internet Control Message Protocol) carries error and diagnostic messages. It has its own IP protocol number (1), so it rides inside IP like a Layer 4 protocol, but it exists to support Layer 3. ping uses ICMP Echo Request and Echo Reply. Routers use ICMP to report "destination unreachable" and "time exceeded".
Every link has a Maximum Transmission Unit (MTU), the largest packet it can carry. Ethernet's is normally 1500 bytes. If a router must forward a packet larger than the next link's MTU, it has two options. If DF is clear, it fragments the packet and the destination reassembles it. If DF is set, which is common because TCP uses path MTU discovery, the router drops the packet and returns an ICMP "Fragmentation Needed" message.
You can find the path MTU with ping:
ip route show # the routing table: default route and connected subnets
ip route get 8.8.8.8 # which route and source address would be used?
traceroute -n example.com # list each router on the path
ping -c 2 -M do -s 1472 example.com # 1472 data + 8 ICMP + 20 IP = 1500 bytes, DF setIf the last command fails but a smaller -s value works, some link on the path has a smaller MTU.
IPv6 in brief
IPv6 uses 128-bit addresses, written in hexadecimal groups such as 2001:db8::1. It has a fixed 40-byte header with no header checksum and no router fragmentation (only the sender fragments). TTL becomes Hop Limit. The same Layer 3 logic applies: prefixes, longest-prefix match, and a default route. A typical LAN subnet is a /64. ARP is replaced by Neighbor Discovery, which runs over ICMPv6, and there is no broadcast. Most networks run IPv4 and IPv6 side by side (dual stack).
Common errors at Layer 3
- Wrong subnet mask. A host with a mask that is too long believes a neighbour is off-subnet and sends traffic to the gateway, or the reverse. Symptoms are one-way or intermittent reachability.
- Missing or wrong default gateway. Local hosts respond, but nothing outside the subnet does.
- Duplicate IP addresses. Two hosts claim one address and traffic flows to one or the other unpredictably.
- Routing loops.
tracerouteshows the same routers repeating until TTL expires. - No return route. The packet reaches the server, but the server does not know how to reply.
pingtimes out even though the forward path works. - ICMP blocked by a firewall. Path MTU discovery fails and large transfers stall while small ones work.
Exercise
A host has the address 10.4.7.200/25. Its destination is 10.4.7.40. Is the destination on the same subnet, and what does the host do first? Then, a router holds routes for 10.4.0.0/16 via R1, 10.4.7.0/24 via R2, and 0.0.0.0/0 via R3. Which next hop does it use for a packet to 10.4.7.40?
Show answer
A /25 has 7 host bits, so blocks are 128 addresses long. 10.4.7.200 is in 10.4.7.128/25 (addresses .128 to .255). 10.4.7.40 is in 10.4.7.0/25, so it is on a different subnet. The host sends the packet to its default gateway, after using ARP to learn the gateway's MAC address. At the router, all three routes match 10.4.7.40, and the longest prefix is the /24, so the next hop is R2.
Exercise
Why does a router decrement the TTL, and what do you see if the TTL reaches zero?
Show answer
The TTL stops packets from circulating forever if a routing loop exists. A router that decrements it to zero drops the packet and sends an ICMP Time Exceeded message to the source. This is the mechanism traceroute uses to identify each hop.