A letter inside envelopes
When your browser sends GET /, that text travels inside a TCP segment, inside an IP packet, inside an Ethernet frame. Each layer adds its own header and only talks to the same layer on the other side — that's encapsulation. It lets Wi-Fi, fibre and 5G carry the same web traffic.
- Application — HTTP, DNS: what you want
- Transport — TCP, UDP: which program, reliably or not
- Network — IP: which computer, across the world
- Link — Ethernet, Wi-Fi: the next hop on this wire
Wrapping and unwrapping
const HEADERS = [
{ layer: "TCP", size: 20 },
{ layer: "IP", size: 20 },
{ layer: "Ethernet", size: 18 },
];
function encapsulate(data, headers) {
let packet = data;
for (const h of headers) packet = { layer: h.layer, size: h.size, payload: packet }; // wrap outward
return packet;
}
function decapsulate(packet) {
const layers = [];
while (typeof packet === "object" && packet !== null && "layer" in packet) {
layers.push(packet.layer);
packet = packet.payload;
}
return { data: packet, layers };
}
function efficiency(headers, dataSize) {
const overhead = headers.reduce((sum, h) => sum + h.size, 0);
return dataSize / (dataSize + overhead);
}