Sub topic 11
What Changes and What Stays the Same at Each Router
This chapter assumes you know the layers (application, transport, network, link) and what encapsulation and decapsulation are. It also assumes you can read an IPv4 header and a MAC address. Here you will follow one packet through routers and sort every header field into "rewritten at each hop" or "preserved end to end".
The core rule
A router works at the network layer. It receives a frame, removes the Ethernet header, reads the IP header, decides where to send the packet, and builds a new Ethernet frame for the next link. The rule has two parts:
- The link-layer header and trailer belong to one link only. Every router discards them and creates new ones.
- The IP packet crosses the whole path. A router edits only a few of its fields, and it does not touch the transport header or the application data.
What a router does with a packet
For each incoming frame, a router performs these steps:
- It checks that the destination MAC address is its own interface address (or broadcast or multicast). Otherwise it ignores the frame.
- It verifies the Ethernet frame check sequence (FCS) and drops the frame if the FCS is wrong. It then removes the Ethernet header and trailer.
- It reads the IPv4 header and verifies the header checksum.
- It decrements the TTL (time to live). If the TTL reaches 0, it drops the packet and sends an ICMP "Time Exceeded" message to the source.
- It recomputes the IPv4 header checksum, because the TTL changed.
- It looks up the destination IP address in its routing table. The longest matching prefix wins. The result is an outgoing interface and a next-hop IP address. For a directly connected network, the next hop is the destination itself.
- It resolves the next hop's MAC address, using ARP for IPv4 if the address is not cached. See the chapter on ARP.
- It builds a new Ethernet header with the outgoing interface's MAC as the source and the next hop's MAC as the destination. The new FCS is computed by the network card.
Step 6 is the only point where the destination IP address matters to the router. The routing decision never looks at the destination MAC address.
Field by field
| Layer | Field | At each router | Why |
|---|---|---|---|
| Link | Destination MAC | Rewritten | Names the next hop on this link only |
| Link | Source MAC | Rewritten | Names the router's outgoing interface |
| Link | EtherType | Usually same (0x0800) | Changes only if the next link carries a different network protocol |
| Link | FCS | Recomputed | It covers the whole frame, which has changed |
| Network | Source IP | Preserved | Identifies the original sender |
| Network | Destination IP | Preserved | Identifies the final destination |
| Network | TTL | Decremented by 1 | Stops packets from looping forever |
| Network | Header checksum | Recomputed | It covers the TTL, which changed |
| Network | Protocol, identification, length | Preserved | Describe the payload |
| Network | DSCP and ECN bits | Preserved or remarked | Network policy may change them, and congested routers may set ECN |
| Transport | Ports, sequence numbers, flags, checksum | Preserved | Only the two end hosts interpret them |
| Application | Data | Preserved | Routers do not read it |
The TCP and UDP checksums also cover a pseudo-header made from the source and destination IP addresses and the protocol. Because those IP fields stay the same, the transport checksum stays valid across routers. TTL is not part of the pseudo-header, so changing it does not affect the transport checksum.
Which addresses mean what
The destination MAC address of a frame leaving Host A is the MAC of its default gateway (the router), not Host B's MAC. Host A uses ARP to learn the gateway's MAC. The destination IP address in the same frame is Host B's.
This split is the main thing to remember:
- IP addresses describe the end-to-end journey.
- MAC addresses describe the next step of that journey.
When you capture traffic to a remote server, the destination MAC in the capture is your router's, and the same server's IP appears in every packet from every router along the way.
Simulating a hop in Python
This script builds a real IPv4 header with a valid checksum, then performs the router's steps on a frame. The payload is a stand-in for a TCP segment. It shows that only the Ethernet header, the TTL, and the checksum change.
import struct
def checksum(header: bytes) -> int:
"""Internet checksum: ones-complement sum of 16-bit words."""
total = 0
for i in range(0, len(header), 2):
total += (header[i] << 8) | header[i + 1]
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def build_ip(src: bytes, dst: bytes, ttl: int, payload: bytes) -> bytes:
header = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(payload),
0, 0, ttl, 6, 0, src, dst)
csum = struct.pack("!H", checksum(header))
return header[:10] + csum + header[12:] + payload
def forward(frame: bytes, out_src_mac: bytes, next_hop_mac: bytes) -> bytes:
packet = frame[14:] # decapsulate: drop Ethernet
ihl = (packet[0] & 0x0F) * 4
if checksum(packet[:ihl]) != 0: # a valid header sums to zero
raise ValueError("bad IP header checksum, packet dropped")
ttl = packet[8]
if ttl <= 1:
raise ValueError("TTL expired, send ICMP Time Exceeded")
new = bytearray(packet)
new[8] = ttl - 1 # decrement TTL
new[10:12] = b"\x00\x00" # zero the checksum field first
new[10:12] = struct.pack("!H", checksum(bytes(new[:ihl])))
# re-encapsulate with a new Ethernet header for the next link
return struct.pack("!6s6sH", next_hop_mac, out_src_mac, 0x0800) + bytes(new)
def show(label: str, frame: bytes) -> None:
dst_mac, src_mac, _ = struct.unpack("!6s6sH", frame[:14])
ip = frame[14:]
print(f"{label}: dst_mac={dst_mac.hex(':')} src_mac={src_mac.hex(':')} "
f"ttl={ip[8]} checksum=0x{ip[10]:02x}{ip[11]:02x} "
f"src_ip={'.'.join(map(str, ip[12:16]))} "
f"dst_ip={'.'.join(map(str, ip[16:20]))} "
f"payload={ip[20:]!r}")
host_a = bytes.fromhex("111111111111")
r1_in = bytes.fromhex("aaaaaaaaaaa1")
r1_out = bytes.fromhex("aaaaaaaaaaa2")
r2_in = bytes.fromhex("bbbbbbbbbbb1")
packet = build_ip(bytes([192, 168, 1, 10]), bytes([203, 0, 113, 5]), 64, b"segment")
frame1 = struct.pack("!6s6sH", r1_in, host_a, 0x0800) + packet
frame2 = forward(frame1, r1_out, r2_in)
show("on link A-R1 ", frame1)
show("on link R1-R2", frame2)Run it and compare the two lines. The MAC addresses, TTL (64 and 63), and checksum differ. The IP addresses and payload are identical.
Observing this on a real network
Traceroute exploits the TTL rule. It sends packets with TTL 1, then 2, then 3, and so on. Each router that drops a packet at TTL 0 reveals itself with an ICMP Time Exceeded reply.
traceroute -n example.comTo see the MAC rewrite, capture on your own machine and look at the Ethernet header (-e):
sudo tcpdump -i eth0 -e -nn -c 3 tcp port 443The destination MAC in each outgoing line is your default gateway's, even though the IP destination is a remote server. Capturing on the router's other interface would show the same IP addresses with different MACs and a TTL that is one lower.
Exceptions and edge cases
- NAT (network address translation). A NAT router rewrites the source IP (and usually the source port) for outbound traffic, and reverses this for replies. It must also update the IP and transport checksums. This breaks the "IP addresses are preserved" rule, and it is the most common exception you will meet at a home or cloud boundary.
- Fragmentation. If the next link's MTU is smaller than the packet and the Don't Fragment bit is not set, an IPv4 router splits the packet. The fragments share the same addresses but get new length, offset, and flag fields. If Don't Fragment is set, the router drops the packet and sends an ICMP "Fragmentation Needed" message.
- Tunnels. A tunnel endpoint adds an outer IP header, so the inner packet's TTL is not decremented while it travels inside the tunnel.
- VLAN tags. A router may add or remove an 802.1Q tag when moving between VLANs, which changes the Ethernet header further.
- Layer 2 switches. A switch forwards frames without changing the Ethernet header or the TTL. Do not confuse a switch hop with a router hop. Only routers decrement TTL.
- Blocked ICMP. Many networks drop ICMP Time Exceeded messages, so traceroute shows
* * *for those hops even though the packets are being forwarded.
Common mistakes
- Expecting the destination MAC of an off-subnet packet to be the remote host's MAC. It is the next router's.
- Expecting the same TTL in captures taken at different points on the path. It falls by one per router.
- Forgetting to recompute the IP checksum after editing a header in a script. The next router drops the packet.
- Assuming the TCP checksum must change at each hop. It does not, unless NAT edits the addresses or ports.
Exercise
Host A sends a packet with an initial TTL of 64 to Host B across two routers. How many Ethernet headers are created for this packet on the way, what is the TTL when it arrives at Host B, and which addresses are identical in every frame?
Show answer
Three Ethernet headers are created: A to Router 1, Router 1 to Router 2, and Router 2 to B. Each router decrements the TTL by 1, so the packet arrives with TTL 62. The source and destination IP addresses (and the TCP ports and payload) are identical in every frame, assuming no NAT. The MAC addresses differ in all three frames.
Exercise
A router receives a packet whose TTL is 1. What does it do, and why does it not simply forward it with TTL 0?
Show answer
It drops the packet and sends an ICMP Time Exceeded message to the source IP address. Forwarding a packet with TTL 0 would defeat the purpose of the field, which is to stop packets that loop between routers from circulating forever.