Sub topic 9
Decapsulation: Unwrapping at the Receiver
Decapsulation is the receiver's side of encapsulation. The sender wrapped application data in a TCP or UDP header, then an IP header, then an Ethernet header. The receiver removes those headers in the opposite order. At each step it checks that the data is meant for it, then uses a field in the header it just read to decide what to hand the rest to.
This chapter assumes you have read the earlier chapters on headers, payloads, and the TCP, IPv4 and Ethernet header formats. You should also be comfortable reading bytes in hexadecimal.
The core idea: each layer reads only its own header
A layer never looks inside its payload. The Ethernet layer treats the IP packet as opaque bytes, and the IP layer treats the TCP segment the same way. This separation lets you replace one layer without touching the others. For example, you can move the same IP packet from Ethernet to Wi-Fi.
Each header carries a field that says what is inside. These are the hand-off fields:
| Layer | Hand-off field | Example value | Meaning |
|---|---|---|---|
| Link (Ethernet II) | EtherType, 2 bytes | `0x0800` | Payload is IPv4 |
| Link (Ethernet II) | EtherType | `0x0806` | Payload is ARP |
| Link (Ethernet II) | EtherType | `0x86DD` | Payload is IPv6 |
| Network (IPv4) | Protocol, 1 byte | `6` | Payload is TCP |
| Network (IPv4) | Protocol | `17` | Payload is UDP |
| Network (IPv4) | Protocol | `1` | Payload is ICMP |
| Transport (TCP/UDP) | Destination port, 2 bytes | `80` | Deliver to the process listening on port 80 |
The receiver uses these fields in turn. The EtherType picks the network-layer handler. The IP protocol number picks the transport-layer handler. The destination port picks the application socket.
The receiver's steps, in order
1. Link layer
The network card receives the electrical, optical or radio signal and rebuilds the frame. It checks the frame check sequence (FCS), a 4-byte CRC at the end of the frame. If the CRC does not match, the card discards the frame. The operating system usually never sees it.
Next, the card compares the destination MAC address with its own. It accepts a frame in these cases:
- The destination is the card's own unicast MAC address.
- The destination is the broadcast address
ff:ff:ff:ff:ff:ff. - The destination is a multicast group the host has joined.
- The card is in promiscuous mode, which capture tools use to see every frame on the wire.
If the frame is accepted, the receiver removes the 14-byte Ethernet header and reads the EtherType to pick the network-layer handler. The FCS is also removed. Capture tools usually do not show it, because the card strips it first.
2. Network layer
The IP layer reads the first byte. The high 4 bits are the version, and the low 4 bits are the IHL, the header length in 32-bit words. An IHL of 5 means 20 bytes. A larger value means the header has options. The IHL tells the receiver where the payload starts, so you must not assume the header is always 20 bytes.
The IP layer then does these checks:
- It verifies the header checksum. It covers only the IP header, not the payload.
- It compares the destination address with the host's own addresses. A host that is not a router drops a packet addressed to someone else. A router instead looks up a route and forwards the packet, as the later chapter on hop-by-hop forwarding explains.
- It reads the Total Length field and uses it to find the end of the packet.
The Total Length step matters. Ethernet requires a minimum payload of 46 bytes, so the sender's card pads short frames with zeros. A small TCP acknowledgement has 20 bytes of IP header and 20 bytes of TCP header, which is only 40 bytes. The card adds 6 padding bytes. The receiver must cut the packet at Total Length, or it would treat the padding as TCP data.
3. Transport layer
For TCP, the receiver reads the data offset field (4 bits, in 32-bit words) to find where the data starts, because TCP options can lengthen the header. It verifies the checksum, which covers the TCP header, the data, and a pseudo-header built from the IP source address, destination address and protocol. The checksum therefore catches a segment delivered to the wrong IP address.
The receiver then finds the socket. A listening socket matches on the destination port. An established connection matches on the full four values: source address, source port, destination address and destination port. If no socket matches, TCP replies with a segment that has the RST flag set. UDP replies instead with an ICMP "port unreachable" message.
For UDP, the header is 8 bytes: source port, destination port, length and checksum. The receiver uses the length field to find the end of the datagram.
4. Application layer
TCP delivers a byte stream, not messages. One send() call on the sender can arrive as several segments, and several send() calls can arrive merged. The application must find message boundaries itself, for example from the HTTP Content-Length header. UDP keeps the boundaries: each datagram arrives as one unit.
Decapsulating in code
This script builds the same kind of frame as the earlier encapsulation example. It then unwraps the frame with the checks a receiver makes. It appends 4 padding bytes to the frame to show why Total Length matters. It does not verify checksums, because the sample frame leaves them as 0.
import struct
BROADCAST = b"\xff" * 6
def build_frame():
http = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
tcp = struct.pack("!HHIIHHHH", 50000, 80, 1, 0, (5 << 12) | 0x018, 65535, 0, 0) + http
ip = struct.pack(
"!BBHHHBBH4s4s", 0x45, 0, 20 + len(tcp), 0, 0, 64, 6, 0,
bytes([192, 168, 1, 10]), bytes([203, 0, 113, 5]),
) + tcp
header = struct.pack(
"!6s6sH", bytes.fromhex("aabbccddeeff"), bytes.fromhex("112233445566"), 0x0800
)
return header + ip
def decapsulate(frame, my_mac, my_ip):
# Link layer
if len(frame) < 14:
raise ValueError("frame shorter than an Ethernet header")
dst_mac, src_mac, ethertype = struct.unpack("!6s6sH", frame[:14])
if dst_mac not in (my_mac, BROADCAST):
return None # not addressed to this host
if ethertype != 0x0800:
raise ValueError(f"unsupported EtherType {ethertype:#06x}")
packet = frame[14:]
# Network layer
if len(packet) < 20:
raise ValueError("packet shorter than an IPv4 header")
version = packet[0] >> 4
ihl = (packet[0] & 0x0F) * 4
if version != 4 or ihl < 20:
raise ValueError("bad IPv4 header")
(total_len,) = struct.unpack("!H", packet[2:4])
if total_len < ihl or total_len > len(packet):
raise ValueError("bad Total Length")
proto = packet[9]
if packet[16:20] != my_ip:
return None # a host that is not a router drops it
segment = packet[ihl:total_len] # cuts off any Ethernet padding
# Transport layer
if proto != 6:
raise ValueError(f"unsupported protocol {proto}")
sport, dport = struct.unpack("!HH", segment[:4])
offset = (segment[12] >> 4) * 4
return {"src_port": sport, "dst_port": dport, "data": segment[offset:]}
frame = build_frame() + b"\x00" * 4 # trailing padding
result = decapsulate(frame, bytes.fromhex("aabbccddeeff"), bytes([203, 0, 113, 5]))
print(result["src_port"], result["dst_port"])
print(result["data"].decode())The function returns None when the frame is not for this host, because a real receiver drops such frames silently. It raises ValueError when the frame is malformed. Real stacks also drop malformed frames, and some count them in statistics.
Common errors and how they appear
- Checksum offload confuses captures. Modern network cards compute checksums on transmit. A capture on the sending host may show "incorrect" checksums, because the packet was recorded before the card filled them in. The data on the wire is fine.
- Capture shows frames larger than the MTU. With segmentation offload, the host hands the card one large segment and the card splits it. A capture taken before the card sees one oversized packet.
- A frame arrives, but nothing reaches the application. Work through the layers in order. Wrong destination MAC means the card dropped it. Wrong destination IP means the IP layer dropped it. No listening port means TCP sent RST. A host firewall can also drop the packet at any of these points.
- Padding read as data. A parser that ignores Total Length will append zero bytes to short packets.
- Assuming fixed header sizes. IP options and TCP options change where the next layer begins. Always compute the offset from IHL and the data offset.
Why the order matters
The receiver must unwrap from the outside in, because each header's position depends on the ones before it. The TCP header is found only after the IP header length is known, and the IP header is found only after the 14-byte Ethernet header is removed. The sender wraps from the inside out, and the receiver reverses exactly that order.
This also explains a security property. A device that reads only up to the IP header, such as a basic router, can forward traffic without understanding TCP or HTTP. A firewall that reads further up the stack sees more but spends more work on each packet.
Exercise
A receiver gets an Ethernet frame whose payload is 46 bytes. The IPv4 header has IHL = 5 and Total Length = 40. The protocol field is 6. (a) How many bytes of the payload are padding? (b) Where does the TCP header start within the IP packet, and how do you know which protocol parses it?
Show answer
(a) The IP packet is 40 bytes long according to Total Length, so 46 - 40 = 6 bytes are padding. The receiver must discard them before passing the segment to TCP. (b) IHL = 5 means the IP header is 5 × 4 = 20 bytes, so the TCP header starts at byte offset 20 of the IP packet. The protocol field value 6 identifies TCP, so the receiver hands bytes 20 to 39 to the TCP handler.
Exercise
A host receives a frame with the correct destination IP address but a destination MAC address that belongs to another host on the same switch. What does the network card do, and why can a packet capture tool still show the frame in some setups?
Show answer
A normal network card drops the frame at the link layer, because the destination MAC is neither its own, the broadcast address, nor a joined multicast group. A capture tool can still show it if the card runs in promiscuous mode, which disables that filter, or if the capture is taken on a mirror port that copies traffic to the capturing host.