Sub topic 2
How Data Is Wrapped on the Way Down and Unwrapped on the Way Up
This chapter assumes you know what a protocol is, what an IP address and a MAC address are, and that you can run Python 3 and simple terminal commands. The chapter on why networks are layered comes before it. Here we look at the mechanism that makes layering work: encapsulation and decapsulation.
The core idea
Each layer does its job by adding its own control information to the data it receives from the layer above. This control information is called a header. Some layers also add a trailer at the end. The layer treats everything it received from above as an opaque payload. It does not read or change that payload.
- Encapsulation is the sending side's process. Data moves down the stack, and each layer wraps the unit from the layer above in its own header (and sometimes trailer).
- Decapsulation is the receiving side's process. Data moves up the stack, and each layer reads its own header, removes it, and passes the payload upward.
The sender and receiver talk "peer to peer" in a logical sense. The transport layer on the sender only ever interprets what the transport layer on the receiver put in a header, and the same holds for every other layer. In reality, the data travels down to the wire and back up.
The journey down the stack
Suppose a program sends the five bytes hello over UDP, which runs on top of IPv4 and Ethernet.
- Application data. The program hands
helloto the operating system through a socket. The layer 5 to 7 work (session handling, encoding, encryption) has already been done by the application or a library. In TCP/IP practice these three layers are not separated in the software. - Transport. The OS adds a UDP header containing the source port, destination port, length, and checksum. The result is a UDP datagram. With TCP, the header would carry sequence numbers, flags, and window size, and the unit is called a segment.
- Network. The OS adds an IPv4 header with the source and destination IP addresses, TTL, a protocol number (17 for UDP, 6 for TCP), and a header checksum. The result is a packet.
- Data link. The network driver adds an Ethernet header (destination MAC, source MAC, EtherType) and the NIC appends a 4-byte frame check sequence (FCS) as a trailer. The result is a frame.
- Physical. The NIC converts the frame to signals: voltage changes, light pulses, or radio modulation.
The nesting on the wire looks like this, from the first byte sent to the last:
| Part | Added by | Typical size |
|---|---|---|
| Ethernet header | Layer 2 | 14 bytes |
| IPv4 header | Layer 3 | 20 bytes (more with options) |
| UDP or TCP header | Layer 4 | 8 bytes (UDP), 20 bytes or more (TCP) |
| Application data | Layers 5 to 7 | Varies |
| Ethernet FCS | Layer 2 | 4 bytes |
The journey up the stack
The receiving NIC turns signals back into bits and finds the frame boundaries. After that, each layer answers two questions: "is this for me?" and "who gets the payload next?"
- Data link. The NIC checks the FCS and discards the frame if it is corrupted. It checks that the destination MAC is its own, a broadcast, or a multicast it has joined. It removes the Ethernet header and uses the EtherType field to choose the next handler (
0x0800is IPv4,0x86DDis IPv6,0x0806is ARP). - Network. The IP layer verifies the header checksum and checks that the destination IP is local. It removes the IP header and uses the protocol field to choose the next handler (6 is TCP, 17 is UDP, 1 is ICMP).
- Transport. The OS reads the destination port and finds the socket bound to it. For TCP it matches the full connection (source and destination address and port) and reorders and acknowledges data. For UDP it just queues the payload.
- Application. The program reads
hellofrom its socket.
Each header contains a "what comes next" field: EtherType, then protocol number, then port. This is how a receiver knows how to read the bytes after a header. Without these fields, decapsulation would be guesswork.
Seeing it in code
The following program builds a complete Ethernet, IPv4, and UDP frame by hand and then decapsulates it. It uses only the standard library and sends nothing on the network. The frame is padded to 60 bytes, which is the Ethernet minimum before the FCS, so you can see how a receiver discards padding.
import struct
def checksum(data):
"""Internet checksum: ones' complement sum of 16-bit words."""
if len(data) % 2:
data += b"\x00"
total = sum(struct.unpack("!%dH" % (len(data) // 2), data))
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def ip_bytes(text):
return bytes(int(part) for part in text.split("."))
def ip_text(raw):
return ".".join(str(b) for b in raw)
def mac_text(raw):
return ":".join(f"{b:02x}" for b in raw)
# ---- Encapsulation (going down) ----
payload = b"hello"
# Layer 4: UDP header = src port, dst port, length, checksum (0 = not used)
udp_len = 8 + len(payload)
udp = struct.pack("!HHHH", 40000, 5000, udp_len, 0) + payload
# Layer 3: IPv4 header, 20 bytes, checksum filled in after the first pass
total_len = 20 + len(udp)
fields = (0x45, 0, total_len, 0, 0, 64, 17) # version/IHL, TOS, length, id, flags, TTL, protocol
src_ip, dst_ip = ip_bytes("192.0.2.10"), ip_bytes("192.0.2.20")
header = struct.pack("!BBHHHBBH4s4s", *fields, 0, src_ip, dst_ip)
header = struct.pack("!BBHHHBBH4s4s", *fields, checksum(header), src_ip, dst_ip)
packet = header + udp
# Layer 2: Ethernet header = dst MAC, src MAC, EtherType (0x0800 = IPv4)
dst_mac = bytes.fromhex("aabbccddeeff")
src_mac = bytes.fromhex("001122334455")
frame = struct.pack("!6s6sH", dst_mac, src_mac, 0x0800) + packet
frame += b"\x00" * (60 - len(frame)) # pad to the Ethernet minimum
print("frame length:", len(frame), "(padded)")
# ---- Decapsulation (going up) ----
dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
print("Ethernet:", mac_text(src), "->", mac_text(dst), "EtherType", hex(ethertype))
assert ethertype == 0x0800, "not IPv4"
ip = frame[14:]
ihl = (ip[0] & 0x0F) * 4
length = struct.unpack("!H", ip[2:4])[0]
assert checksum(ip[:ihl]) == 0, "bad IP header checksum"
print("IP:", ip_text(ip[12:16]), "->", ip_text(ip[16:20]), "protocol", ip[9], "ttl", ip[8])
segment = ip[ihl:length] # the length field lets us drop the padding
sport, dport, ulen, _ = struct.unpack("!HHHH", segment[:8])
print("UDP:", sport, "->", dport)
print("payload:", segment[8:ulen])Expected output:
frame length: 60 (padded)
Ethernet: 00:11:22:33:44:55 -> aa:bb:cc:dd:ee:ff EtherType 0x800
IP: 192.0.2.10 -> 192.0.2.20 protocol 17 ttl 64
UDP: 40000 -> 5000
payload: b'hello'Notice three things. Each decapsulation step slices off a header and passes the rest upward. The "what comes next" fields (0x0800, protocol 17) drive the path. The IP total length, not the frame size, determines where the real data ends.
What changes on each hop
Encapsulation does not happen only once. When a packet crosses a router, the router decapsulates up to layer 3 and encapsulates again on the outgoing link.
- The layer 2 header and trailer are replaced at every hop. The source MAC becomes the router's outgoing interface, and the destination MAC becomes the next hop's. The FCS is recalculated.
- The layer 3 header mostly survives. Source and destination IP addresses stay the same (unless NAT rewrites them). The TTL drops by 1, and the header checksum is recomputed because the TTL changed.
- The layer 4 header and the payload are untouched. A plain router never reads them. Firewalls, load balancers, and NAT devices are exceptions, because they look at ports or rewrite them.
This is why MAC addresses identify the next device on the same link, while IP addresses identify the final destination. A switch, by contrast, reads only the Ethernet header and forwards the frame without changing it.
Overhead, MTU, and fragmentation
Every header takes space. A link has a maximum transmission unit (MTU), which is the largest layer 3 packet it can carry. For standard Ethernet the MTU is 1500 bytes. The 14-byte Ethernet header and 4-byte FCS sit outside that limit.
For TCP over IPv4 with no options, 1500 minus 20 (IP) minus 20 (TCP) leaves 1460 bytes for application data. This value is the maximum segment size (MSS). TCP negotiates it during the handshake so that segments fit in one packet.
UDP has no equivalent mechanism. If an application sends a UDP datagram larger than the path MTU, IPv4 may fragment it into several packets, and the receiver must reassemble them. If any fragment is lost, the whole datagram is lost. Many networks also drop fragments, so applications that use UDP usually keep datagrams small.
Extra encapsulation reduces the room available. A VLAN tag adds 4 bytes to the Ethernet header. A VPN or tunnel wraps a whole packet inside another packet, adding another set of headers. A tunnel over a 1500-byte link may therefore offer only about 1400 bytes to inner traffic. Ignoring this is a classic source of connections that work for small requests and hang on large ones.
Common mistakes
- Treating layers 5 to 7 as separate wrappers. In the OSI model they are three layers. In practice a TLS library and an HTTP library produce one stream of bytes. TLS does add its own record headers around application data, but no operating system adds a "session header".
- Thinking the destination MAC is the final host. Across a router it is the next hop's MAC. Only the IP destination stays constant end to end.
- Mixing up the "what comes next" fields. EtherType selects the layer 3 protocol. The IP protocol field selects the layer 4 protocol. The port selects the application. They are three different lookups at three different layers.
- Assuming a frame's size equals the IP length. Padding can follow the packet, so always trust the length fields inside the headers.
- Forgetting the trailer. The FCS is added by the NIC. Packet captures usually do not show it, because the hardware verifies it and strips it before software sees the frame.
Exercises
Exercise
A host sends a TCP segment with 1000 bytes of application data over IPv4 and Ethernet, with no IP or TCP options and no VLAN tag. How many bytes is the complete frame on the wire, including the FCS, and which layer added each part?
Show answer
1000 bytes of data plus a 20-byte TCP header (layer 4) gives 1020 bytes. A 20-byte IPv4 header (layer 3) gives a 1040-byte packet. A 14-byte Ethernet header and a 4-byte FCS (layer 2) bring the frame to 1058 bytes. The packet is within the 1500-byte MTU, so no splitting is needed.
Exercise
A packet goes from Host A through one router to Host B. Which of these change at the router: source MAC, destination MAC, source IP, destination IP, TTL, UDP destination port? Assume no NAT.
Show answer
The source MAC, destination MAC, and TTL change. The source MAC becomes the router's outgoing interface and the destination MAC becomes Host B's. The TTL decreases by 1, and the IP header checksum is recalculated as a result. The source IP, destination IP, and UDP destination port stay the same.
Exercise
In the Python example, why does the decapsulation code slice the segment with ip[ihl:length] instead of ip[ihl:]?
Show answer
The frame was padded to 60 bytes, so ip[ihl:] would include zero bytes after the real data. The IP total length field marks where the packet ends, so slicing to it removes the padding. Without it, the program would treat padding as part of the UDP datagram.
Exercise
A receiver gets a frame with EtherType 0x0800, then finds protocol 6 in the IP header. Name the next header it expects and the field it uses to hand the data to the right program.
Show answer
Protocol 6 means TCP, so the next header is a TCP header. The OS uses the TCP destination port, together with the source address and port for an established connection, to find the socket that receives the data.