Sub topic 3
Encapsulation: wrapping data layer by layer
This chapter assumes you know what a network and an IP address are, can read bytes in hexadecimal, and can run commands in a terminal. It covers how a message is built for sending, one layer at a time. Later chapters cover each header in detail, so here the focus is the process and the rules that connect the layers.
The core idea
Encapsulation is the process of placing the data from one layer inside a new unit that the layer below creates. The lower layer adds its own control information, called a header, in front of the data it was given. The data it was given is now the payload of the new unit.
The lower layer does not look inside the payload. It treats the payload as opaque bytes. Ethernet does not know whether it carries IPv4 or IPv6, and IP does not know whether it carries a web request or a video stream. Each layer only needs its own header to do its job.
This separation is why you can change one layer without touching the others. A web browser works the same over Wi-Fi, a cable or a mobile link, because only the lowest layer's wrapping changes.
Wrapping step by step
Suppose a browser sends an HTTP request. The host wraps it in four steps:
- The application produces the data, for example the text of an HTTP request.
- The transport layer prepends a TCP header. The result is a TCP segment.
- The network layer prepends an IPv4 header. The result is an IP packet.
- The link layer prepends an Ethernet header and, in most cases, appends a trailer. The result is an Ethernet frame.
The frame is what the network card turns into signals on the wire or radio waves.
Read the diagram from top to bottom on the sender. The innermost content is always the application data, and the outermost header belongs to the link layer. The receiver reads in the opposite direction, outermost first.
What each layer adds
Every header contains two kinds of information. Some fields say where the unit is going. Other fields say what is inside it, so the receiver can pick the right software to process the payload. That second group is what makes unwrapping possible.
| Layer | Unit | Header size (typical) | Addressing it adds | Field that names the payload |
|---|---|---|---|---|
| Transport | TCP segment | 20 bytes without options | Source and destination port | Destination port selects the application |
| Network | IPv4 packet | 20 bytes without options | Source and destination IP address | Protocol field (6 = TCP, 17 = UDP) |
| Link | Ethernet II frame | 14 bytes, plus a 4-byte trailer | Source and destination MAC address | EtherType (0x0800 = IPv4, 0x86DD = IPv6) |
The last column explains how a receiver knows what comes next. The EtherType value says "an IPv4 packet follows." The IPv4 protocol value says "a TCP segment follows." The TCP destination port says "give this data to the program listening here." Each field is a hint for the layer above.
The trailer in the table is the frame check sequence (FCS), a 4-byte checksum computed over the whole frame. The receiving card uses it to detect corruption and drops damaged frames. Most capture tools do not show it, because the network card removes it before the operating system sees the frame.
Overhead: the cost of wrapping
Headers use bandwidth. With no options, a TCP segment over IPv4 over Ethernet adds 20 + 20 + 14 = 54 bytes of header, plus the 4-byte FCS, for 58 bytes in total. A 37-byte HTTP request becomes a 91-byte frame before the FCS. A tiny payload has high relative overhead. A payload of 1460 bytes, the usual maximum for TCP on a 1500-byte link, has low overhead. This is one reason bulk transfers fill packets and chat protocols try to batch small messages.
Building a frame by hand
The program below does encapsulation manually with the struct module. It builds the TCP, IPv4 and Ethernet headers, prints the size after each step, then reverses the process. The checksums are left as zero, because this demo is about structure, not about being sent on a real network.
import struct
http = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
# Transport: TCP header (20 bytes, no options) + application data.
# Flags 0x018 = PSH + ACK. The checksum is left as 0 in this demo.
tcp = struct.pack("!HHIIHHHH", 50000, 80, 1, 0, (5 << 12) | 0x018, 65535, 0, 0) + http
print("segment bytes:", len(tcp))
# Network: IPv4 header (20 bytes, no options) + TCP segment.
# Protocol 6 = TCP. The header checksum is left as 0 in this demo.
src_ip = bytes([192, 168, 1, 10])
dst_ip = bytes([203, 0, 113, 5])
ip = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(tcp), 0, 0, 64, 6, 0, src_ip, dst_ip) + tcp
print("packet bytes: ", len(ip))
# Link: Ethernet II header (14 bytes) + IP packet. EtherType 0x0800 = IPv4.
# The network card adds the frame check sequence, so it is omitted here.
dst_mac = bytes.fromhex("aabbccddeeff")
src_mac = bytes.fromhex("112233445566")
frame = struct.pack("!6s6sH", dst_mac, src_mac, 0x0800) + ip
print("frame bytes: ", len(frame))
# Decapsulate: peel the headers off in the reverse order.
_, _, ethertype = struct.unpack("!6s6sH", frame[:14])
packet = frame[14:]
ihl = (packet[0] & 0x0F) * 4
(total_len,) = struct.unpack("!H", packet[2:4])
ttl, proto = packet[8], packet[9]
segment = packet[ihl:total_len]
sport, dport = struct.unpack("!HH", segment[:4])
offset = (segment[12] >> 4) * 4
data = segment[offset:]
print(hex(ethertype), ttl, proto, sport, dport)
print(data.decode())Running it prints 57 for the segment, 77 for the packet and 91 for the frame. Each number is the previous one plus 20, 20 and 14. The line 0x800 64 6 50000 80 confirms the EtherType, the TTL, the protocol number, and the two ports. The last lines print the original HTTP request.
Three details in the code matter beyond this example:
- Every
structformat starts with!, which means network byte order (big-endian). Protocol headers store multi-byte numbers with the most significant byte first. - The IPv4 length field,
20 + len(tcp), counts the header plus everything inside it. Each layer's length must be computed after the inner layer is complete, which is why wrapping always runs from the inside out. - The receiver finds the TCP header by reading the IP header length (
ihl) and the payload by reading the TCP data offset. Headers can be longer than their minimum when options are present, so a receiver must read these fields rather than assume 20 bytes.
Order and direction
Encapsulation follows a fixed order because each layer depends on information from the one below it. Ports are needed before the IP header makes sense of the segment, and the IP header must exist before the Ethernet frame can carry it. Operating systems do this in the network stack: the application calls a socket function, and the kernel adds the headers.
Decapsulation reverses the sequence. The card receives a frame and checks its FCS and destination MAC address. The stack removes the Ethernet header, reads the EtherType and hands the payload to IP. IP checks the destination address, removes its header, reads the protocol number and hands the payload to TCP or UDP. The transport layer reads the port and delivers the data to the right socket. A later chapter covers this direction in full.
Common errors
- Thinking each layer copies the data. Real stacks avoid copies where they can. The conceptual model shows nesting, but implementations often reserve space for headers in front of the data in a buffer. The model is still correct for what appears on the wire.
- Mixing up the units. Calling every piece a "packet" is common in casual speech. When you read captures, the distinction helps: a segment has ports, a packet has IP addresses, and a frame has MAC addresses. The next chapter names these precisely.
- Forgetting that lengths must be recalculated. If you build packets by hand, as in the code above, a wrong IP total length or TCP data offset makes the receiver read the wrong bytes or discard the packet.
- Assuming the header size is fixed. IPv4 and TCP headers both grow when options are present. Always take the size from the header-length fields.
- Ignoring byte order. Writing a port as little-endian produces the wrong number. Port 80 packed in the wrong order is read as 20480.
Summary of the rules
- A layer adds a header (and sometimes a trailer) to the unit it receives from above.
- The lower layer never interprets the payload.
- Each header carries a field that says what the payload is: a port, a protocol number or an EtherType.
- Wrapping runs from the application down to the link layer. Unwrapping runs from the link layer up.
Exercise
A TCP segment carries 100 bytes of application data and has no options. It is sent in an IPv4 packet with no options inside an Ethernet II frame. Not counting the FCS, how large is the frame, and what value does the IPv4 total length field hold?
Show answer
The segment is 20 + 100 = 120 bytes. The IPv4 total length field counts the IP header and the segment: 20 + 120 = 140. The Ethernet header adds 14 bytes, so the frame is 154 bytes without the FCS (158 with it).
Exercise
A receiver gets a frame with EtherType 0x0800, an IPv4 protocol field of 17, and destination port 53. Name the layers it passes through and what each field tells it.
Show answer
The EtherType 0x0800 tells the link layer that the payload is an IPv4 packet. The protocol value 17 tells IP that the payload is a UDP datagram. UDP then uses destination port 53 to deliver the data to the program listening on that port, normally a DNS service.