Sub topic 4
Encapsulation and decapsulation: how data moves through the stack
This chapter assumes you know what a client and a server are, can run commands in a terminal, and have met the idea of layered models from the earlier chapters. You should also know the names of the four TCP/IP layers: link, internet, transport, and application. Here you will follow one piece of data down the stack on the sender, across the network, and back up the stack on the receiver.
The core idea
Each layer does one job and talks to the layer above and below it through a narrow interface. To do its job, a layer needs to attach information for its peer layer on the other side. That information is a header. Some protocols, such as Ethernet, also add a trailer at the end.
Encapsulation is the process of wrapping the data from the layer above with this layer's header (and sometimes a trailer). The wrapped result is handed down to the next layer, which treats it as an opaque payload and wraps it again. Decapsulation is the reverse. The receiver strips one header per layer, checks it, and passes the remaining payload upward.
Two rules make the whole system work:
- A layer only reads and writes its own header. It never looks inside the payload it carries.
- A header on the sender is read by the same layer on the receiver, or by a device along the path that operates at that layer.
The second rule explains why a layer feels as if it talks directly to its peer. The TCP code on your laptop appears to talk to the TCP code on the server. In reality, its messages travel down through every lower layer and back up on the other side.
Following one request down the stack
Suppose a browser sends an HTTP request to a web server. The steps on the sender look like this.
- Application layer. The browser produces the application data, for example the text
GET /index.html HTTP/1.1and its headers. This is the message. - Transport layer. TCP splits the data into pieces that fit the path, and adds a TCP header to each piece. The header holds the source port, destination port, sequence number, acknowledgment number, flags, and a checksum. The result is a segment.
- Internet layer. IP adds an IP header holding the source and destination IP addresses, a time-to-live (TTL) value, and a protocol field that says "the payload is TCP". The result is a packet.
- Link layer. Ethernet adds a header with the destination and source MAC addresses and an EtherType field that says "the payload is IPv4". It also adds a trailer with a frame check sequence (FCS). The result is a frame.
- Physical transmission. The network interface turns the frame's bits into signals on the wire, fibre, or radio.
The next table shows what the frame contains from the outside in. The first row is what appears first on the wire.
| Order on the wire | Part | Added by | Key fields |
|---|---|---|---|
| 1 | Ethernet header | Link layer | Destination MAC, source MAC, EtherType |
| 2 | IP header | Internet layer | Source IP, destination IP, TTL, protocol |
| 3 | TCP header | Transport layer | Source port, destination port, sequence number, flags |
| 4 | Application data | Application layer | HTTP request text |
| 5 | Ethernet trailer | Link layer | Frame check sequence |
The outermost header belongs to the lowest layer. The application data sits in the middle, which is why encapsulation is often drawn as nested boxes.
Building the nesting in code
The Scapy library models this nesting directly. Its / operator stacks one layer on top of another, from the link layer upward.
from scapy.all import Ether, IP, TCP
pkt = Ether() / IP(dst="192.0.2.10") / TCP(dport=80, flags="S")
pkt.show()pkt.show() prints one block per header: Ether, IP, and TCP. Read it from top to bottom and you are reading the frame from the outermost header inward. Fields you did not set, such as the source MAC address and the source port, receive defaults when Scapy builds the packet. The flags="S" value sets the SYN flag, so this is the first packet of a TCP handshake. It has no application data.
Scapy shows that a packet is just a list of headers. Your own programs rarely build headers by hand. Normally the operating system does it, as the next example shows.
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.sendto(b"hello", ("127.0.0.1", 9999))The program supplies only the application data (hello), an address, and a UDP port. The operating system adds the UDP header, the IP header, and the link-layer header below it. The socket interface is the boundary between the application layer, which your code owns, and the transport layer, which the kernel owns.
Following the data back up
The receiver reverses every step. This is decapsulation.
- The network interface receives the bits and reassembles the frame.
- The link layer checks the FCS. If it does not match, the frame is discarded silently. It then checks whether the destination MAC address is its own, a broadcast, or a multicast address it has joined. If not, it drops the frame. Otherwise it removes the Ethernet header and trailer and reads the EtherType to decide which protocol gets the payload.
- The internet layer checks the IP header, including the destination address. It removes the IP header and reads the protocol field to find that the payload is TCP.
- The transport layer uses the destination port, together with the source address and port, to find the right socket. It verifies the checksum, orders the data by sequence number, and removes the TCP header.
- The application receives the byte stream. For TCP this is a stream, not a list of segments. The application usually never sees segment boundaries.
The key point is demultiplexing. Each header carries a field that names the protocol above it: EtherType for the link layer, the protocol number for IP, and the port for the transport layer. These fields tell the receiver which handler gets the payload next.
What happens at a router
A router does not decapsulate all the way up. It works at the internet layer. For each frame it does the following:
- Accepts the frame because the destination MAC is its own interface.
- Removes the Ethernet header and trailer.
- Reads the IP header, decrements the TTL, and recomputes the IP header checksum. It looks up the destination address in its routing table.
- Builds a new Ethernet header and trailer for the next hop, then sends the frame out of the chosen interface.
Three consequences follow, and they cause many confusing observations in captures:
- The IP source and destination addresses normally stay the same from end to end. The MAC addresses change at every hop.
- The TCP segment inside is untouched, so the router does not need to understand ports.
- The TTL goes down by one at every router. At zero, the router drops the packet and may send an ICMP Time Exceeded message back. The
traceroutetool uses this behavior.
Devices that rewrite more than this, such as a NAT gateway or a firewall that tracks connections, do look at the transport header. NAT changes the IP addresses and often the ports as well. That is why such devices break the clean "the router only reads layer 3" picture.
Size limits: MTU, MSS, and fragmentation
Headers use space. Each link has a maximum transmission unit (MTU), the largest IP packet it can carry. On standard Ethernet the MTU is 1500 bytes. This number covers the IP header and everything inside it, but not the Ethernet header or trailer.
With a 20-byte IPv4 header and a 20-byte TCP header (no options), the largest TCP payload in one packet is 1500 − 20 − 20 = 1460 bytes. This value is the maximum segment size (MSS). TCP announces its MSS during the handshake so that the sender builds segments that fit.
| Item | Typical size in bytes |
|---|---|
| Ethernet header | 14 |
| Ethernet FCS trailer | 4 |
| IPv4 header (no options) | 20 |
| TCP header (no options) | 20 |
| UDP header | 8 |
| Standard Ethernet MTU | 1500 |
Common edge cases:
- Tunnels add headers. A VPN or other tunnel wraps a whole packet inside another packet. The extra header reduces the usable payload, so the effective MTU shrinks. If the sender does not adapt, large packets are dropped or fragmented.
- IPv4 fragmentation. If a packet is larger than the next link's MTU and the Don't Fragment bit is not set, a router splits it into fragments. The receiver's internet layer reassembles them before passing the data up. Fragmentation is costly, and losing one fragment loses the whole packet.
- Path MTU discovery. Senders usually set the Don't Fragment bit. A router that cannot forward the packet sends back an ICMP message, and the sender lowers its packet size. If a firewall blocks those ICMP messages, large transfers can hang while small ones work. This is a classic symptom.
- UDP has no segmentation. UDP does not split data for you. A large datagram relies on IP fragmentation, so applications that use UDP usually keep messages small.
- Jumbo frames. Some networks use an MTU of about 9000 bytes to reduce per-packet overhead. Every device on the path must agree on it.
Observing it with a capture
You can see all of this with a packet capture tool. The following command captures five TCP packets on port 80 and prints the link-layer addresses (-e) and the IP and TCP header fields (-v).
sudo tcpdump -nn -e -v -c 5 'tcp port 80'Each output line starts with the Ethernet part: source MAC, destination MAC, and the EtherType (for example ethertype IPv4 (0x0800)) and frame length. The next part shows the IP header with ttl, the protocol and the addresses. The last part shows the TCP header with ports, flags, sequence numbers, and the window. You are reading the headers in the order they were added, from the outside in.
Compare the same flow captured on two sides of a router. The IP addresses match, the TTL differs by one, and the MAC addresses are different. That confirms the router rebuilt the link-layer header.
Common mistakes
- Saying "packet" for everything. Each layer has its own name for its unit: frame, packet, segment, or datagram. The names are covered in a later chapter. Use them carefully when you read a capture.
- Expecting MAC addresses to survive the whole path. They only identify the two ends of one link.
- Thinking TCP preserves message boundaries. It does not. Two
sendcalls may arrive as onerecv, and onesendmay arrive as several. - Forgetting overhead. Header bytes count against the MTU, and tunnels add more.
- Assuming the receiver sees what the sender sent. NAT, load balancers, and proxies can change headers along the way.
Summary
- Encapsulation adds one header per layer on the way down. Ethernet also adds a trailer.
- Decapsulation removes them in reverse order, using the EtherType, IP protocol, and port fields to pick the next handler.
- Routers strip and rebuild the link-layer header at every hop and leave the IP and transport headers largely unchanged, apart from the TTL and checksum.
- Headers consume the MTU, and tunnels, NAT, and fragmentation are the usual edge cases.
Exercise
A client sends 3000 bytes of application data over TCP on a standard Ethernet link (MTU 1500) with IPv4 and TCP headers of 20 bytes each and no options. How many segments does TCP need to send, and how large is the biggest Ethernet frame on the wire, counting the 14-byte header and the 4-byte FCS?
Show answer
The MSS is 1500 - 20 - 20 = 1460 bytes. 3000 / 1460 is about 2.05, so TCP needs 3 segments (1460, 1460, and 80 bytes). A full segment makes a 1500-byte IP packet. Adding the 14-byte Ethernet header and the 4-byte FCS gives a largest frame of 1518 bytes.
Exercise
A packet leaves your laptop, crosses one router, and reaches a server. In a capture taken on the laptop and another taken on the server, which of these fields are the same and which differ: source IP, destination MAC, TTL, destination port?
Show answer
The source IP and destination port are the same, because the router does not rewrite them (assuming no NAT). The destination MAC differs, because the laptop addresses the frame to the router and the router builds a new frame addressed to the server. The TTL is lower by one on the server side, because the router decrements it.
Exercise
Large file downloads hang, but small web pages load fine, and the path crosses a VPN tunnel. Which encapsulation-related cause would you check first, and why?
Show answer
Check the path MTU. The tunnel adds an extra header, which reduces the usable payload. If full-size packets are dropped and the ICMP messages that report the problem are blocked by a firewall, path MTU discovery fails. Small packets fit and work, while large transfers stall. Lowering the MTU or MSS on the tunnel usually fixes it.