Module 2 · Beginner · How data travels: network models

Packets, frames and encapsulation

Encapsulation explained: how data becomes segments, packets, frames and bits, what each header holds, MTU and overhead, and an IPv4 header built in Python.

By theprogrammers team · · 10 min read

When you post a parcel, the shop puts your item in a box, the courier sticks a shipping label on it, and the van company puts it in a sack labelled for the next city. At each hand-over, the outer layer changes, but the item inside is never touched. Networks do the same with data. Your browser's request gets wrapped in a TCP header, then an IP header, then an Ethernet or Wi-Fi frame, and every router along the way swaps the outer frame while leaving the inside alone. This wrapping is called encapsulation.

It's also where all those PDU names come from: segments, packets and frames are the same data with different wrappers. This lesson walks one request through every layer, shows what each header holds, explains MTU and why headers cost bandwidth, and builds a real IPv4 header byte by byte in Python.

What you need first: the OSI model and the TCP/IP model. Bits, bytes and binary helps with the Python section.

Key terms

  • Encapsulation: adding a layer's header (and sometimes trailer) around the data from the layer above.
  • Decapsulation: removing those headers, one layer at a time, at the receiving end.
  • Payload: the data a header is wrapped around.
  • Segment / datagram: the transport-layer unit: TCP segment or UDP datagram.
  • Packet: the internet-layer unit: an IP header plus its payload.
  • Frame: the link-layer unit: a link header, the packet, and a trailer.
  • MTU (maximum transmission unit): the largest packet a link can carry. 1,500 bytes on standard Ethernet.

The wrapping, layer by layer

Opening a web page sends an HTTP request. On its way down the stack:

LayerAddsResult is calledKey header fields
ApplicationThe HTTP request itself (encrypted by TLS for HTTPS)Data / messageMethod, path, headers
TransportTCP header (20 bytes, usually)SegmentSource port, destination port, sequence number, flags
InternetIP header (20 bytes for IPv4, 40 for IPv6)PacketSource IP, destination IP, TTL, protocol
LinkEthernet header (14 bytes) and trailer (4 bytes)FrameSource MAC, destination MAC, type, checksum (FCS)
PhysicalNothing; turns the frame into signalsBits

The same thing, as nested boxes:

data = "GET / HTTP/1.1"
segment = f"[TCP 52344->443 | {data}]"
packet = f"[IP 192.168.1.10->203.0.113.5 | {segment}]"
frame = f"[ETH a4:5e:60:11:22:33->00:1a:2b:3c:4d:5e | {packet} | FCS]"

for name, unit in [("Data", data), ("Segment", segment), ("Packet", packet), ("Frame", frame)]:
    print(f"{name:8}{unit}")
Data    GET / HTTP/1.1
Segment [TCP 52344->443 | GET / HTTP/1.1]
Packet  [IP 192.168.1.10->203.0.113.5 | [TCP 52344->443 | GET / HTTP/1.1]]
Frame   [ETH a4:5e:60:11:22:33->00:1a:2b:3c:4d:5e | [IP 192.168.1.10->203.0.113.5 | [TCP 52344->443 | GET / HTTP/1.1]] | FCS]

(203.0.113.5 comes from a block of addresses reserved for documentation, and the MAC addresses are made up.)

What's in each header

TCP header (transport)

FieldPurpose
Source portWhich program sent it; usually a random high number like 52344
Destination portWhich program should get it, such as 443 for HTTPS
Sequence numberPosition of this data in the stream, so it can be put back in order
Acknowledgement numberHow much data has been received from the other side
FlagsSYN (start), ACK (acknowledge), FIN (finish), RST (reset)
Window sizeHow much more data the receiver can accept right now
ChecksumDetects damaged segments

A UDP header is much simpler: just source port, destination port, length and checksum, 8 bytes in all.

IP header (internet)

FieldPurpose
Version4 or 6
Total lengthSize of the whole packet
TTL (time to live)Lowered by 1 at every router; the packet is dropped at 0, so lost packets don't circle for ever
ProtocolWhat's inside: 6 = TCP, 17 = UDP, 1 = ICMP
Source and destination IPWhere it's from and where it's going
Header checksumDetects a damaged header
FieldPurpose
Destination and source MACThe next device on this link, and this device
EtherTypeWhat's inside: 0x0800 = IPv4, 0x86DD = IPv6, 0x0806 = ARP
PayloadThe IP packet: 46 to 1,500 bytes
FCS (frame check sequence)A checksum at the end; damaged frames are dropped

Build a real IPv4 header in Python

Headers are just bytes in an agreed order. Python's struct module packs numbers into bytes exactly as a network stack does. This builds a real 20-byte IPv4 header, calculates its checksum the way routers do, then reads it back:

import socket
import struct

def ip_checksum(header):
    total = 0
    for i in range(0, len(header), 2):
        total += (header[i] << 8) + header[i + 1]       # add up 16-bit words
    while total >> 16:
        total = (total & 0xFFFF) + (total >> 16)        # fold any carry back in
    return ~total & 0xFFFF                              # one's complement

payload = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
total_length = 20 + 20 + len(payload)                   # IP header + TCP header + data

header = struct.pack(
    "!BBHHHBBH4s4s",
    0x45,            # version 4, header length 5 x 4 = 20 bytes
    0,               # type of service
    total_length,
    1,               # identification
    0,               # flags and fragment offset
    64,              # TTL
    6,               # protocol: 6 = TCP
    0,               # checksum, filled in below
    socket.inet_aton("192.168.1.10"),
    socket.inet_aton("203.0.113.5"),
)
header = header[:10] + struct.pack("!H", ip_checksum(header)) + header[12:]

fields = struct.unpack("!BBHHHBBH4s4s", header)
print(len(header), "bytes:", header.hex(" ", 4))
print("version", fields[0] >> 4, "| header", (fields[0] & 0xF) * 4, "bytes | total", fields[2], "bytes")
print("TTL", fields[5], "| protocol", fields[6], "(TCP)")
print(socket.inet_ntoa(fields[8]), "->", socket.inet_ntoa(fields[9]))
print("checksum valid:", ip_checksum(header) == 0)

The output shows the header's 20 bytes in hex (grouped 4 bytes at a time), then the fields read back from them:

20 bytes: 4500004d 00010000 4006b02e c0a8010a cb007105
version 4 | header 20 bytes | total 77 bytes
TTL 64 | protocol 6 (TCP)
192.168.1.10 -> 203.0.113.5
checksum valid: True

! in the format string means network byte order (big-endian: most significant byte first), which every internet protocol uses. B is 1 byte, H is 2 bytes and 4s is 4 raw bytes. A header whose checksum is correct adds up to zero when checked, which is how routers spot a damaged header and drop it. c0a8010a is 192.168.1.10 in hex: c0 = 192, a8 = 168.

Decapsulation, and what routers change

At the receiving computer, each layer checks and removes its own header and passes the payload up: the network card checks the frame's FCS and removes the Ethernet header; the IP layer checks the destination address and removes the IP header; TCP puts segments in order and hands the bytes to the browser or server.

In between, every router does a partial decapsulation:

  1. Receive the frame, check the FCS, and remove the Ethernet header and trailer.
  2. Read the IP header: lower the TTL by 1, update the header checksum, and look up the next hop.
  3. Wrap the packet in a new frame with new MAC addresses for the next link (which might be fibre or Wi-Fi rather than Ethernet).

So MAC addresses change at every hop, while the IP addresses stay the same from end to end (unless NAT rewrites them, which the IP addressing module explains). Switches don't even go that far: they read only the frame's MAC addresses and forward it unchanged.

MTU, MSS and overhead

Every link has a maximum packet size, the MTU: 1,500 bytes on standard Ethernet. Take away 20 bytes of IP header and 20 bytes of TCP header, and each segment can carry at most 1,460 bytes of data, called the MSS (maximum segment size). A large download is cut into many 1,460-byte pieces.

Headers take up room that could have been data. With 58 bytes of Ethernet, IP and TCP headers and trailer per frame:

headers = 14 + 4 + 20 + 20          # Ethernet header + FCS + IPv4 + TCP
for data_bytes in [1460, 500, 40]:
    frame = data_bytes + headers
    print(f"{data_bytes:>4} bytes of data -> {frame:>4}-byte frame, {data_bytes / frame:.1%} useful")
1460 bytes of data -> 1518-byte frame, 96.2% useful
 500 bytes of data ->  558-byte frame, 89.6% useful
  40 bytes of data ->   98-byte frame, 40.8% useful

Big packets carry data efficiently; tiny ones are mostly header. That's one reason chatty apps that send many tiny messages waste bandwidth, and why VPNs and tunnels, which add their own extra headers, slightly lower the maximum data per packet. If a packet is bigger than a link's MTU, it must be split (fragmented) or dropped, and MTU mismatches are a classic cause of "small pages load, big ones hang" problems.

Practice

  1. Put these in order from the application down: frame, data, packet, segment.
Show the answer

Data, segment, packet, frame (then bits on the wire).

  1. Which addresses change at each router hop, and which stay the same?
Show the answer

The MAC addresses (link layer) change at every hop, because each frame only travels one link. The source and destination IP addresses stay the same end to end, unless NAT changes them.

  1. What's the MSS on a link with an MTU of 1,400 bytes, with IPv4 and TCP headers of 20 bytes each?
Show the answer

1,400 − 20 − 20 = 1,360 bytes.

  1. Change the Python header to use protocol 17 and TTL 128. What do those mean?
Show the answer

Protocol 17 means the payload is UDP instead of TCP. TTL 128 means the packet can pass through up to 128 routers before being dropped (Windows uses 128 as its default TTL; Linux uses 64). The checksum changes too, and checksum valid still prints True because it's recalculated.

  1. Why does every IP packet have a TTL?
Show the answer

If routing goes wrong, a packet could loop between routers for ever, using up bandwidth. Each router lowers the TTL by 1 and drops the packet when it reaches 0, so loops end. traceroute uses this deliberately to discover each router on a path.

Interview questions

What is encapsulation in networking?

The process by which each layer adds its own header (and possibly trailer) to the data from the layer above before passing it down: application data becomes a TCP segment, then an IP packet, then a link-layer frame, then bits. The receiver reverses it, each layer removing its header and passing the payload up.

What is the difference between MTU and MSS?

MTU is the largest packet (layer 3) a link can carry, typically 1,500 bytes on Ethernet. MSS is the largest amount of TCP payload in one segment, the MTU minus IP and TCP headers, typically 1,460 bytes for IPv4.

What changes in a packet as it passes through a router?

The link-layer frame is replaced with a new one for the next link, with new source and destination MAC addresses. In the IP header, the TTL is decremented and the header checksum recalculated. Source and destination IP addresses are unchanged, unless the router performs NAT.

Key takeaways

  • Encapsulation wraps data in a header at each layer: data becomes a segment (TCP), a packet (IP), a frame (Ethernet or Wi-Fi), then bits.
  • TCP headers carry ports and sequence numbers; IP headers carry IP addresses, TTL and protocol; frames carry MAC addresses and a checksum.
  • Routers replace the frame at every hop, so MAC addresses change while IP addresses stay the same.
  • Headers are just bytes in network byte order; Python's struct can build and read them.
  • MTU limits packet size (1,500 bytes on Ethernet); headers are overhead, so tiny packets waste bandwidth.

Frequently asked questions

What is the difference between a packet and a frame?

A packet is the internet-layer unit, with IP addresses, which travels end to end. A frame is the link-layer unit, with MAC addresses, which travels only one hop; it carries the packet inside it and is replaced at every router.

Can I see encapsulation on my own computer?

Yes. Install Wireshark, capture traffic while opening a website, and click any packet. Wireshark shows each layer as a separate section: the Ethernet or Wi-Fi frame, the IP header, the TCP header and the application data.

Why is network byte order big-endian?

It was chosen when the internet protocols were designed, so every machine sends multi-byte numbers the same way regardless of its own CPU's order. Many CPUs, including x86 and most ARM chips, are little-endian internally, so the network stack converts.

What to learn next

  1. Measure how fast data moves in bandwidth, latency and throughput.
  2. Revise the layers in the TCP/IP model.
  3. Practise binary and hex in bits, bytes and binary.