Skip to content

Chapter 1: Network Layering Model


Metadata Card

DimensionValue
Difficulty
PrerequisitesAny programming language basics, basic system programming concepts
KeywordsLayering, Encapsulation, OSI, TCP/IP, Protocol Stack
Code LanguagePython (primary) / Java (diff window)

Your Progress

"You climb out of the mage tower's cellar and stand on a mist-shrouded plain. Spell Scroll Village, Incantation Forest, Mana Core City — all these worlds lie across this wilderness. But they can't talk to each other. You need a path — the Magic Post Road is the communication pipeline connecting all these worlds."

You've been staying in your mage tower, writing spell calls and passing parameters, understanding how mana moves between spell echo space and core arrays. The core array beneath your feet is an isolated city, with all spell energy circulating within its walls.

Now it's time to leave the city.

Spell energy must travel from your mage staff, through the moat array, out from the beacon tower's tip, hop onto a mana beam, and finally reach another mage tower's core array. The problem: this post road doesn't exist yet. Between two mage towers, there's no shared energy, no common resonance frequency — only a single magic conduit cable.

You can't just call send(source, target, message) — that's the gods' perspective. Reality: you must build the post road, erect beacon towers, light teleportation arrays, and layer by layer send the spell message out.

This is what layering does.

Chapter Layering

  • Must Read: Why layering (what each layer does), encapsulation and decapsulation, the four-layer story of a browser request
  • Optional: OSI Seven Layers vs TCP/IP Four Layers, Socket type relationships
  • Advanced: Manually constructing protocol frames (ProtocolStack class)

This chapter will NOT require you to master: Scapy analysis, raw socket programming, bit-level protocol details

Encounter: A Chat Program Without Layering

Suppose you have a serial cable directly connecting two machines. You want A to send a message to B. The code seems perfect:

python
def send_via_serial(data: str, port: str):
    with open(port, 'wb') as f:
        f.write(data.encode('utf-8'))

def recv_via_serial(port: str) -> str:
    with open(port, 'rb') as f:
        return f.read().decode('utf-8')

But you'll soon encounter six problems: (1) data corruption, (2) flow control, (3) addressing, (4) session recovery, (5) encoding, (6) multiplexing. If you cram all these into one program, the code becomes tangled within two weeks.

Core Insight: No one can solve all these problems at once. We negotiate by layers. Each layer deals with one type of problem, provides services to the layer above, exposes standard interfaces to the layer below. Any layer can be replaced as long as the protocol stays the same.

Memory Anchor: Layering = separation of concerns. Lower layers don't understand upper layer data meaning; upper layers don't care about the physical medium below.

OSI Seven Layers vs TCP/IP Four Layers

OSI Seven-Layer Model (Textbook)

LayerNameTaskAnalogy
7ApplicationFor users, HTTP/FTP/SMTPSpell name on a magic letter
6PresentationEncoding/encryption/compressionAdding a sealing spell to the letter
5SessionEstablish/maintain/end sessionsWho casts first, who waits for echo
4TransportEnd-to-end reliable/unreliable transportMagic pigeon tracking spell
3NetworkRouting and addressingWhich beacon tower the letter goes through
2Data LinkFrame transmission between adjacent beaconsFrom one station to the next
1PhysicalBit stream transmission over mediumMana pulses in magic conduit cable

Real World: TCP/IP Four-Layer Model

┌──────────────────────────────────┐
│  4  Application Layer            │  ← HTTP, DNS, SSH, TLS
│  3  Transport Layer              │  ← TCP, UDP
│  2  Internet Layer               │  ← IP, ICMP, ARP
│  1  Network Access Layer         │  ← Ethernet, Wi-Fi
└──────────────────────────────────┘

OSI's Layers 5/6 are merged into the Application Layer in TCP/IP — in reality, not many protocols need an independent presentation layer.

Encapsulation & Decapsulation

Data traveling down adds a header at each layer:

Application:  [HTTP HEADER | HTTP BODY]
Transport:    [TCP HEADER | HTTP HEADER | HTTP BODY]
Network:      [IP HEADER | TCP HEADER | HTTP HEADER | HTTP BODY]
Link:         [ETH HEADER | IP HEADER | TCP HEADER | HTTP BODY | ETH TRAILER]

The ProtocolStack class (full Python implementation in the chapter source) simulates this — each layer prepends headers with MAC addresses, IP addresses, ports, and sequence numbers. A simple HTTP GET request traverses all four layers.

Diff Window: Java

Java uses java.net package hierarchy to hint at protocol layering:

java
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Socket sock = new Socket("example.com", 80);
sock.setSoTimeout(5000);
sock.setTcpNoDelay(true);

Java hides the physical/link layer differences inside the SocketImpl factory. Python's socket module is lower-level — you choose AF_INET vs AF_INET6 vs AF_PACKET.

Pass Challenges

Challenge 1: scapy Packet Capture

bash
pip install scapy

Script to capture curl http://example.com and print each layer's header:

python
from scapy.all import sniff, Ether, IP, TCP, Raw

def packet_analysis(pkt):
    if Ether in pkt:
        print(f"[L2] Src MAC: {pkt[Ether].src} → Dst MAC: {pkt[Ether].dst}")
        if IP in pkt:
            print(f"[L3] {pkt[IP].src}{pkt[IP].dst} (TTL={pkt[IP].ttl})")
            if TCP in pkt:
                print(f"[L4] TCP {pkt[TCP].sport}{pkt[TCP].dport}")
                if Raw in pkt:
                    print(f"[L7] Data: {pkt[Raw].load[:80]}")

sniff(filter="host example.com", count=3, prn=packet_analysis)

Challenge 2: Layered Fault Diagnosis

"Video is lagging" — Wi-Fi full, ping OK, DNS OK, but video rate far below bandwidth. Which layer?

(Hint: Check UDP loss → TCP window scaling → router QoS)

Challenge 3: Protocol Stack Deep Comparison

Use tcpdump -X or Wireshark to find: MAC addresses, TTL/total length/checksum, source port/seq/ack/window.

Acceptance Checklist

  • [ ] Why layer instead of a monolithic program?
  • [ ] Which OSI layers are merged in TCP/IP?
  • [ ] What does "encapsulation" mean at each layer?
  • [ ] Which protocol at L4? L3? for a browser request?
  • [ ] Video stuttering — which layer's component to suspect?

Common Sticking Points

Sticking PointClarification
"Encapsulation is wasteful nesting"Each header is ~20-60 bytes vs 1500 MTU = ~4% overhead, worth it
"TCP/IP vs OSI — which is correct?"Both correct, different abstractions. OSI is detailed, TCP/IP is the real standard
"Why no Application Layer 'header'?"HTTP headers ARE the L7 header — we just don't call it that
"Layering is software, not related to hardware"NIC firmware does L2 frame checksum and addressing (L2 offloading)

Traveler's Notes

The first time I saw tcpdump showing an IP header with TTL=64, I felt a strange familiarity — it looked just like the time_slice in the kernel's task_struct. Computer designers keep using the same mindset: give everything a boundary, let it die or retry within that boundary. Layering embodies these boundaries.

Remember: layering isn't a perfect solution — it's a workable solution. A network engineer's real job is knowing which layer is lying, and going to that layer to capture packets.

Next: Socket Programming

You now know how data is packaged and leaves the city. Next: how to wait for and receive it at the other end — Socket programming.

Built with VitePress | Software Systems Atlas