AlgoViz

How the OSI and TCP/IP models work

medium 40 min

A network request is a message wrapped in headers, one per layer, like dolls inside dolls.

Nesting dolls: one request, four headers

1:24Reel coming soon

Theory

Read or listen first. About 3 min.

What it is

A layer model splits the job of moving data between computers into parts. Each part has one responsibility and talks only to the part above and the part below. Because of that, Wi-Fi can replace a cable without anyone changing TCP, and HTTP/2 can replace HTTP/1.1 without anyone changing IP.

There are two models you must know. OSI has seven layers: physical, data link, network, transport, session, presentation and application. It is the vocabulary: when people say "an L4 load balancer" or "an L7 firewall", they are using OSI numbers. TCP/IP has four layers: link, internet, transport and application. RFC 1122 describes them, and it is what runs on your laptop, your phone and every server.

Each layer puts its own header in front of the data it gets from above. That is encapsulation. The unit of data has a different name at each layer: a frame at layer 2, a packet at layer 3, a segment (TCP) or datagram (UDP) at layer 4, and a message at the top. Each layer also has its own kind of address: a MAC address, an IP address, a port number, and a name or URL.

Why it exists

Without layers, every program would have to know about cables, radio, routes and lost packets. With layers, a browser only asks for "a reliable stream to port 443 on this address", and the kernel and the network do the rest. New link types, new transports and new apps can be added one at a time.

For engineers in production, the layers are a debugging map. "Ping works but the site does not load" already tells you that layers 1 to 3 work for ICMP, so you look at DNS, TCP, TLS or HTTP. Interviewers for SRE, production engineering and full-stack roles use this language all the time: "Is this an L4 or an L7 problem?"

A short history

  1. 1974

    Kahn and Cerf publish "A protocol for packet network intercommunication". The first written version was handed out in September 1973. Their single TCP was later split into IP, for addressing and forwarding, and TCP, for reliable streams.

  2. 1980-1981

    UDP (RFC 768, 28 August 1980), IP (RFC 791, September 1981) and TCP (RFC 793, September 1981) are published.

  3. 1983

    On 1 January the ARPANET switches from NCP to TCP/IP in one go, the date that RFC 801 set as the goal.

  4. 1984

    ISO publishes the OSI Basic Reference Model as International Standard 7498. RFC 1008 from 1987 cites it as "IS 7498 [ISO84b]". The CCITT version, X.200, followed in 1988 and was revised in 1994.

  5. 1989

    RFC 1122, from October, describes the four layers of the Internet suite and warns that strict layering is "an imperfect model".

  6. 2018-2022

    TLS 1.3 (RFC 8446, August 2018), QUIC over UDP (RFC 9000, May 2021) and a new TCP standard, RFC 9293 (August 2022), which replaces RFC 793.

Inside this chapter

Layer
One responsibility in the stack, with a fixed interface above and below.
Protocol
The rules two peers at the same layer follow: message format, order and meaning. TCP talks to TCP, IP to IP.
PDU
Protocol data unit: what one layer sends. Frame, packet, segment or datagram, message.
Encapsulation
Putting the data from the layer above behind a new header. Decapsulation removes it again on the other side.
Header
Bytes in front of the data that the peer layer reads: addresses, ports, numbers, lengths, checksums.
MTU
Maximum transmission unit: the largest IP packet a link carries in one frame. 1500 bytes on Ethernet.
MSS
Maximum segment size: the most TCP data in one segment. MTU minus the IP and TCP headers, so 1460 for 1500.
Port
A 16-bit number that picks one program's socket on a host. Server ports are well known (443); client ports are short-lived.
Hop
One router on the path. Each hop lowers the TTL by one.
Socket
The program's handle on one end of a conversation, named by protocol, address and port.

How it works

Step through the idea, or press Play.

Step 1 of 6

App writes bytes. HTTP request into a socket

Understand it

Start here

Dolls inside dolls

Asha wants to order from a shop across the country. The order is a short note. To make it travel, Asha packs it the way nesting dolls are packed: a small doll inside a bigger one inside a bigger one. Each doll has a tag, and each helper on the way reads only the tag they need. Lee works at the shop. Max, Sam and Noor are helpers on the way.

Packing an order in nesting dolls
GET /ordersfor the shop'sorder deskA note

Every helper opens only the dolls they must. Only Asha and Lee ever read the note.

Two models

Seven names, four layers that run

OSI is a reference model: a set of names agreed before the Internet won. TCP/IP grew from working code. RFC 1122 says its application layer covers what OSI calls presentation and application, and in practice OSI's session layer lives there too. The bottom two OSI layers, physical and data link, form TCP/IP's link layer.

The two models side by side

OSI layerTCP/IP layerProtocolsUnitAddressRuns in
7 ApplicationApplicationHTTP, DNS, SSHmessagename, URLthe program
6 PresentationApplicationTLS, compression, encodingsrecordnonelibraries (OpenSSL)
5 SessionApplicationTLS sessions, HTTP/2 streamsnonenonelibraries
4 TransportTransportTCP, UDP, QUIC (on UDP)segment, datagramportkernel (QUIC: user space)
3 NetworkInternetIPv4, IPv6, ICMPpacketIP addresskernel
2 Data linkLinkEthernet, Wi-Fi, ARPframeMAC addressdriver and network card
1 PhysicalLinkcopper, fibre, radiobitsnonenetwork card, cable
Where TLS and ARP belong is argued about. TLS does OSI's presentation job but runs in the app. ARP carries layer 3 addresses inside layer 2 frames. Say so in an interview instead of forcing them into one box.

How the layers map

Three OSI layers become one application layer. Two become one link layer.

What "L4" and "L7" mean at work

  • L4 load balancer

    Looks at addresses and ports and forwards whole TCP connections or UDP flows. It never reads the HTTP request. Fast, simple, protocol-blind.

  • L7 load balancer

    Ends TCP and TLS, reads the HTTP request, and routes by host, path or header. It opens a second connection to the backend. More features, more work.

  • L3 and L4 firewall

    Allows or drops by address, protocol and port: "allow TCP 443 from anywhere".

  • L7 firewall

    Reads requests: blocks a path, a header or a pattern in a body. Needs to see inside TLS, so it must end TLS.

More on how load balancers choose a backend: load balancing.

One request in seven moves

  1. 1

    The app writes

    The program writes the HTTP request into a socket. To the app it is just bytes in a buffer (L7).

  2. 2

    TCP cuts and numbers

    The kernel's TCP adds ports and a sequence number, and cuts long data into segments of at most one MSS (L4).

  3. 3

    IP addresses and routes

    IP adds both addresses and a TTL, and the routing table picks the next hop (L3).

  4. 4

    ARP and the frame

    ARP finds the next hop's MAC. Ethernet or Wi-Fi adds the frame header and the check (L2).

  5. 5

    Bits on the medium

    The card turns the frame into signals on copper, light in fibre, or radio (L1).

  6. 6

    Each hop

    Switches read only L2. Routers strip L2, read L3, lower the TTL and add a new L2. NAT also rewrites L3 and L4.

  7. 7

    The server unwraps

    Its card and kernel remove the headers in reverse order and deliver the bytes to the listening socket.

Byte by byte

Encapsulation with real numbers

Our example request is 57 bytes of HTTP: GET /orders HTTP/1.1, a Host line, an Accept line and an empty line. Follow it down the stack. Every number below was computed by the program in the Code tab.

One request, one header at a time

LayerAddsBytes addedTotal
HTTPthe request itself5757
TLS 1.3 record5-byte record header, 1 byte of content type, 16-byte tag2279
TCPports, sequence and ack numbers, flags, window, checksum2099
IPv4version, length, ID, flags, TTL, protocol, checksum, two addresses20119
Ethernetdestination MAC, source MAC, type 0x080014133
Ethernet trailerframe check sequence (CRC), added by the card4137
Assumptions: TLS 1.3 with a 16-byte authentication tag, and TCP without options. Linux usually adds 12 bytes of TCP timestamps to every segment, which makes the frame 149 bytes.

How much of a full frame is data?

MSS=1500−20−20=146014601460+20+20+14+4=14601518≈96.2%\text{MSS} = 1500 - 20 - 20 = 1460 \qquad \frac{1460}{1460 + 20 + 20 + 14 + 4} = \frac{1460}{1518} \approx 96.2\%
With 12 bytes of timestamps the data is 1,448 bytes, 95.4%. A 100,000-byte response needs 69 full segments and about 104,000 bytes on the wire.

The smallest frames are mostly header. A pure TCP acknowledgment carries no data: 14 + 20 + 20 = 54 bytes. RFC 894 says the data field of an Ethernet frame is at least 46 bytes, so the card pads 40 bytes of IP and TCP with 6 zero bytes: 60 bytes, plus the 4-byte check, makes the 64-byte minimum frame.

Text
0000  02 00 00 00 00 fe 02 00 00 00 00 01 08 00 45 00    Ethernet: dst MAC, src MAC, type 0800 | IPv4 starts: 450010  00 28 1c 46 40 00 40 06 20 c0 c0 a8 01 17 cb 00    length 40, ID, DF, TTL 64, proto 6, checksum, 192.168.1.23, 203.0.0020  71 0a c9 3a 01 bb 00 00 03 e8 00 00 00 00 50 02    113.10 | TCP: port 51514, port 443, seq 1000, ack 0, offset 5, SYN0030  fa f0 e8 49 00 00                                  window 64240, checksum, urgent 0
A SYN built byte by byte by our program: 14 bytes of Ethernet, 20 of IPv4, 20 of TCP. All addresses are made up.
Text
$ tcpdump -nn -e -vv -r ours.pcap02:00:00:00:00:01 > 02:00:00:00:00:fe, ethertype IPv4 (0x0800), length 54: (tos 0x0, ttl 64, id 7238,  offset 0, flags [DF], proto TCP (6), length 40)    192.168.1.23.51514 > 203.0.113.10.443: Flags [S], cksum 0xe849 (correct), seq 1000, win 64240, length 0
We wrote that frame into a capture file and let tcpdump 4.99.1 decode it. It agrees on every field and says both checksums are correct.

The IPv4 header, field by field

FieldBitsIn our SYNWhy it is there
Version, header length4 + 445: version 4, 5 words = 20 bytesOptions make the header longer, up to 60 bytes
Type of service (DSCP, ECN)800Priority marks and congestion signals
Total length160028 = 40Header plus data, so padding can be ignored
Identification, flags, fragment offset16 + 3 + 131c46, 4000: Don't FragmentPutting fragments back together
Time to live840 = 64Lowered at every router, dropped at zero: no endless loops
Protocol806 = TCPWhich layer 4 gets the data: 6 TCP, 17 UDP, 1 ICMP
Header checksum1620c0Covers the header only. Every router recomputes it
Source and destination32 + 32c0a80117, cb00710a192.168.1.23 and 203.0.113.10
Field sizes from RFC 791. The bytes are from our SYN above.

The TCP header, field by field

FieldBitsIn our SYNWhy it is there
Source and destination port16 + 16c93a = 51514, 01bb = 443Which programs on the two hosts
Sequence number32000003e8 = 1000Number of the first byte in this segment
Acknowledgment number320Next byte expected from the other side
Data offset, reserved4 + 450: 5 words = 20 bytesWhere the data starts, after any options
Flags802 = SYNCWR, ECE, URG, ACK, PSH, RST, SYN, FIN
Window16faf0 = 64240How many more bytes the sender of this segment can take
Checksum16e849Covers header, data and the IP addresses
Urgent pointer160Rarely used
Field sizes and flag names from RFC 9293. Real SYNs also carry options such as MSS, window scale and timestamps, so a Linux SYN is usually longer than ours.

Layer 2

Ethernet and ARP: reaching the next door

Layer 2 only moves a frame across one link: from the laptop to the router, or between two ports of a switch. It uses 48-bit MAC addresses, which say nothing about where in the world a machine is. A switch learns which MAC address sits behind which port and forwards frames by that table. It never reads the IP header.

The laptop knows the server's IP address, 203.0.113.10, but it cannot send a frame to an IP address. Its routing table says the next hop is the gateway, 192.168.1.1, so it needs the gateway's MAC address. ARP (RFC 826, November 1982) finds it: a broadcast question, a direct answer, and a cache.

ARP for the gateway

EtherType 0x0806 marks ARP, 0x0800 IPv4 and 0x86DD IPv6 (IANA registry). IPv6 uses Neighbor Discovery over ICMPv6 instead of ARP.

What ip neigh tells you

StateMeaningWhat to think
REACHABLEConfirmed recentlyLayer 2 to this neighbour is fine
STALEUsable but not confirmed latelyNormal. The kernel checks it again when it is used
DELAY, PROBEBeing checked nowNormal for a moment
INCOMPLETEAsked, no answer yetThe neighbour is down, unplugged, or on another VLAN
FAILEDGave up after too many unanswered probesLayer 2 problem. A ping by IP will fail too
State names from the ip-neighbour manual. A wrong subnet mask often shows up here: the host sends ARP for an address that is not on its link.

Layer 3

IP and routing: crossing many networks

IP gets a packet from one host to another across any number of networks. Every packet carries both addresses. Each router looks up the destination in its routing table, picks the longest matching prefix, and sends the packet one hop further. IP promises nothing: packets can be lost, repeated or reordered. RFC 1122 calls it a datagram service "providing no end-to-end delivery guarantees".

What a router does with one packet

RFC 791: every module that handles the packet lowers the TTL, and at zero the packet is destroyed. Linux starts at 64.
Text
$ ip routedefault via 192.168.1.1 dev wlan0192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.23$ ip route get 203.0.113.10203.0.113.10 via 192.168.1.1 dev wlan0 src 192.168.1.23
Illustrative output with our made-up addresses. The /24 route matches only the local network; everything else falls to the default route. ip route get asks the kernel which route it would really use.

traceroute turns the TTL into a tool. It sends packets with TTL 1, then 2, then 3. Each router that lowers a TTL to zero drops the packet and sends back ICMP Time Exceeded, type 11 in RFC 792, which reveals its address. A row of stars means that hop did not answer, which is common and not always a problem. Routing, ICMP and loss in production are covered in IP delivery.

IPv4 and IPv6 at a glance

IPv4IPv6
Address size32 bits: 203.0.113.10128 bits: 2001:db8::10
Header20 to 60 bytes40 bytes fixed, extras in extension headers
Hop limitTTLHop Limit, same job
Finding a neighbour's MACARPNeighbor Discovery over ICMPv6
Fragmentationrouters may split, unless DFonly the sender splits (RFC 8200)
Smallest link MTU68 bytes in theory1280 bytes, required on every link
Home networksprivate addresses and NATusually global addresses, a firewall instead of NAT
The layers are the same. Only the layer 3 header and its helpers change. 2001:db8::/32 is the documentation prefix.

Hop by hop

What changes on the way and what does not

The road of one request

In Asha's home network the laptop at 192.168.1.23 sends a frame to the router's MAC with TTL 64. The switch reads only layer 2 and passes the same frame to the home router. The router does routing and NAT on layers 2, 3 and 4 and sends the packet into the internet with source 198.51.100.7 port 40001, new MAC addresses and TTL 63. ISP routers read layers 2 and 3 and lower the TTL at each hop. In the shop's network the load balancer at 203.0.113.10 port 443 receives it and opens a new TCP connection to the API server.
Red marks the leg where NAT rewrites addresses. Each device reads only the layers written under its name.

Which fields change at each device

FieldSwitchRouterNAT routerLoad balancer (L7)
Source and destination MACsamenew pairnew pairnew pair
TTLsameminus 1minus 1new packet
Source IPsamesamepublic addressits own address
Source portsamesamenew portnew connection
Destination IP and portsamesamesamethe backend's
TCP sequence numberssamesamesamenew connection, new numbers
Encrypted HTTP bytessamesamesamedecrypted, read, encrypted again
A router changes only what it must. An L7 load balancer is the end of one conversation and the start of another.

Layer 4

TCP: a reliable stream from unreliable packets

TCP turns lost, repeated and reordered packets into an ordered stream of bytes for one program. Every byte has a sequence number. The receiver says which byte it expects next, and the sender sends again what was not acknowledged in time. Before any data, the two sides agree on their starting numbers with the three-way handshake.

The handshake, data and close

A SYN counts as one sequence number, so the answer acknowledges 1001. Our numbers. Real starting numbers are random, so that nobody off the path can guess them (RFC 9293).

The life of a TCP connection

Simplified: FIN_WAIT stands for FIN-WAIT-1 and FIN-WAIT-2. ss shows these states. Many CLOSE_WAIT sockets mean the program forgot to close them.

What a failed connect tells you

You seeOn the wireLikely layer and cause
Connection refused, at onceSYN, then RST backL4: host is up, nothing listens on that port
Timed out after about two minutesSYN, SYN again, no answerL3 or a firewall that drops silently, or the host is down
No route to hostICMP unreachable, or ARP failsL3 or L2: no route, or the neighbour does not answer
Connected, then TLS errorhandshake done, TLS alertL6/L7: certificate, name or version
Connected, HTTP 502 or 504full exchange with the proxyL7: the proxy's backend failed or was slow
connect(2): ECONNREFUSED means "no one listening on the remote address". Linux sends 6 SYN retries by default. The tcp(7) manual puts that at about 127 seconds; the current kernel documentation, with its newer linear first retries, says 131 seconds.

Reliability, flow and congestion in one minute

  • Retransmission

    If no ACK arrives within the retransmission timeout, send again and double the timeout. RFC 6298: start at 1 second, never below 1 second. Three duplicate ACKs trigger a fast retransmit without waiting.

  • Flow control

    The receiver's window says how many bytes it can still take. The sender never has more unacknowledged data in flight than that.

  • Congestion control

    The sender's own limit, the congestion window, guesses what the network can carry. It grows quickly at first (slow start), then slowly, and shrinks after loss (RFC 5681).

  • Deep dives

    Windows: TCP delivery windows. Algorithms: transport congestion. States and timers: TCP connection lifetime.

Why the window limits speed

throughput≤windowRTT65,535×8 bit0.1 s≈5.2 Mbit/s\text{throughput} \le \frac{\text{window}}{\text{RTT}} \qquad \frac{65{,}535 \times 8\ \text{bit}}{0.1\ \text{s}} \approx 5.2\ \text{Mbit/s}
A window of 64 KiB on a 100 ms path, our numbers. That is why window scaling exists and is on by default in Linux: windows can grow far past 64 KiB.

Slow start: round trips for a 100 KB answer

⌈100,0001,460⌉=69 segments10+20+40=70≥69⇒3 round trips\left\lceil \frac{100{,}000}{1{,}460} \right\rceil = 69\ \text{segments} \qquad 10 + 20 + 40 = 70 \ge 69 \Rightarrow 3\ \text{round trips}
Assumes an initial window of 10 segments (RFC 6928) that doubles every round trip, and no loss. Why short requests over long distances feel slow even on a fast link.

Layer 4

UDP, ports and sockets

UDP (RFC 768) adds only 8 bytes: two ports, a length and a checksum. RFC 768 says delivery and duplicate protection are not guaranteed. That is a feature for DNS queries, games, video calls and QUIC, which build exactly the reliability they need on top.

TCP and UDP

TCPUDP
Header20 bytes, up to 60 with options8 bytes
Setuphandshake: one round tripnone
Deliveryordered, no gaps, no doubleseach datagram alone, maybe lost
Boundariesa byte stream, no message edgesone send is one datagram
Speed controlflow and congestion controlnone: the app must be polite
Used byHTTP/1.1, HTTP/2, SSH, databasesDNS, QUIC and HTTP/3, VoIP, games

A port picks the program. A socket is the program's handle. A TCP connection is named by four values: source IP, source port, destination IP, destination port. The server keeps one listening socket on port 443 and gets a new socket for every connection. The client's port is an ephemeral port chosen by the kernel: on Linux from 32768 to 60999 by default.

How many connections from one client to one server port?

60,999−32,768+1=28,232 ports per (source IP, destination IP, destination port)60{,}999 - 32{,}768 + 1 = 28{,}232\ \text{ports per (source IP, destination IP, destination port)}
A busy proxy talking to one backend can run out, especially with many sockets waiting in TIME_WAIT. More addresses or more destination ports raise the limit.

Rewriting headers

NAT: many devices, one public address

Home networks use private addresses from RFC 1918 (February 1996): 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. They are not routed on the internet. The home router rewrites the source address and port of every outgoing packet and keeps a table, so it knows where each reply belongs. RFC 3022 calls this NAPT: network address port translation.

NAT on the way out and back

The server never sees the private address. A packet from outside that matches no table entry is dropped, so nobody outside can start a connection without a static mapping.

NAT breaks the clean layering on purpose: a layer 3 device changes layer 4 fields, and it must fix the TCP checksum, because that checksum covers the addresses too. It is also why idle connections through NAT die: the router forgets an entry after a quiet while, and the next packet has no home. Keepalives or shorter idle timeouts fix it.

Size limits

MTU, fragmentation and black holes

Ethernet carries at most 1500 bytes of IP packet (RFC 894). Tunnels and VPNs add their own headers, so their MTU is smaller. A packet bigger than the next link's MTU can be split into fragments by IPv4 routers, unless the Don't Fragment bit is set. In IPv6 only the sender may fragment, and every link must carry at least 1280 bytes (RFC 8200).

Path MTU discovery

RFC 1191, November 1990. If a firewall drops that ICMP message, the sender never learns, and large packets vanish silently: an MTU black hole.

MTU and cost for a 100,000-byte answer

MTUMSSSegmentsBytes on the wireUseful
1500 (Ethernet)146069104,00296.2%
1400 (a tunnel, our example)136074104,29295.9%
9000 (jumbo frames)896012100,69699.3%
Computed by our program: 20 bytes IP, 20 bytes TCP, 18 bytes Ethernet per segment. Jumbo frames help only if every device on the path supports them.

Upper layers

Where DNS, TLS and HTTP sit

  • DNS

    An application protocol that usually runs over UDP port 53 and falls back to TCP port 53 for big answers. RFC 1035 limited UDP messages to 512 bytes; EDNS allows more. It runs before the connection, so a DNS failure looks like "could not resolve host". See DNS in production, DNS and how DNS works.

  • TLS

    Runs on top of TCP and needs only "a reliable, in-order data stream" (RFC 8446). It encrypts, proves the server's identity with a certificate, and sends the server name (SNI) in the first message. OSI would call it presentation. See TLS and service identity.

  • HTTP

    The application message: method, path, headers, body, status. Its meaning is the same in HTTP/1.1, 2 and 3 (RFC 9110). HTTPS uses TCP port 443 by default. See HTTP transports.

  • QUIC

    Moves reliability, streams and TLS 1.3 into user space on top of UDP (RFC 9000). It blurs layers 4 to 6 on purpose, and its connection IDs survive an address change. See HTTP/2 and HTTP/3.

All together

What really happens when you type a URL

Type https://example.com and press Enter. The browser parses the URL, finds the name, opens a connection, makes it private, and asks. Every step uses all the layers below it.

From Enter to the first byte

Three round trips after DNS with TCP and TLS 1.3: the handshake, TLS, then the request. HTTP/3 over QUIC joins the first two.

Time before the first byte

t≈tDNS+1⏟TCP+1⏟TLS 1.3+1⏟HTTP RTT3×50 ms=150 mst \approx t_{\text{DNS}} + \underbrace{1}_{\text{TCP}} + \underbrace{1}_{\text{TLS 1.3}} + \underbrace{1}_{\text{HTTP}}\ \text{RTT} \qquad 3 \times 50\ \text{ms} = 150\ \text{ms}
Our numbers: a 50 ms round trip and a DNS answer from cache. A CDN close to the user makes the round trip short; see CDN.
Text
$ dig +noall +answer example.com Aexample.com.    300  IN  A  172.66.147.243example.com.    300  IN  A  104.20.23.154$ curl -4 --http1.1 -sv -o /dev/null https://example.com* Trying 104.20.23.154:443...* Connected to example.com (104.20.23.154) port 443        <- L4: handshake done* (304) (OUT), TLS handshake, Client hello (1):            <- L6: TLS starts* (304) (IN), TLS handshake, Server hello (2):* SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256*  subject: CN=example.com                                 <- identity checked* ALPN: server accepted http/1.1> GET / HTTP/1.1                                           <- L7: the request> Host: example.com< HTTP/1.1 200 OK                                          <- L7: the answer
Our own run on 27 November 2026, shortened, with arrows added by us. Your addresses will differ: this name is served by a CDN.

Now put a capture beside it. Below is what tcpdump -nn -e would show for the same kind of request from our laptop, cut to one line per packet. The rows are illustrative, built from our made-up addresses, and the headers present in each row are what matters.

One HTTPS request, packet by packet

#PacketHeaders presentLayer doing the work
1ARP who has 192.168.1.1Ethernet, ARPL2: finding the gateway (only if not cached)
2ARP reply: at 02:00:00:00:00:feEthernet, ARPL2
3DNS query A shop.example, UDP 53Ethernet, IPv4, UDP, DNSL7 message over L4 UDP
4DNS answer 203.0.113.10Ethernet, IPv4, UDP, DNSL7
5 to 7SYN, SYN+ACK, ACK to port 443Ethernet, IPv4, TCPL4 handshake
8TLS ClientHello with SNIEthernet, IPv4, TCP, TLSOSI L6 job inside TCP data
9 to 10ServerHello, certificate, FinishedEthernet, IPv4, TCP, TLSL6
11HTTP request, encryptedEthernet, IPv4, TCP, TLS (HTTP inside)L7 inside L6
12HTTP response, encryptedsameL7
13 to 16FIN, ACK, FIN, ACKEthernet, IPv4, TCPL4 close
On the return path the MAC addresses, the IP addresses and the ports are all swapped, and the TTL starts again from the server's own value. The DNS server address depends on your network.

Tools

Seeing each layer on Linux

Who owns each layer on one host

Inside one Linux host, the app in user space hands HTTP bytes to the TLS library, which writes records into the kernel's socket buffers. The kernel's TCP and UDP code makes segments, IP and routing make packets, netfilter hooks decide whether they may pass, the neighbour table supplies the next hop MAC, and the qdisc queues frames for the driver and network card in hardware. Each part is labelled with the command that shows it.
User space owns HTTP and TLS. The kernel owns TCP, IP, filtering and neighbours. The card owns the bits. More: the Linux network path.

One command per layer

LayerQuestionCommandLook at
L1/L2Is the link up?ip -br link, ethtool eth0UP, LOWER_UP, speed, error counters
L2Do we know the next hop's MAC?ip neighREACHABLE or STALE, not FAILED
L3Do we have an address and a route?ip -br addr, ip route get IPthe src address, via, dev
L3Where does the path break?tracepath -n host, mtrlast hop that answers, pmtu
L4Is anyone listening? Is it healthy?ss -tlnp, ss -tniLISTEN on the port; rtt, retrans, cwnd
L7 (DNS)Does the name resolve?dig name, dig @8.8.8.8 namestatus NOERROR, answer, query time
L6/L7Does TLS and HTTP work?curl -v https://host/connected, certificate, status code
AllWhat is really on the wire?tcpdump -nn -e -i any host HSYN, RST, retransmits, ICMP
tcpdump -e prints the link-level header and -i any captures on every interface on Linux (tcpdump manual).
Shell
# Change something and watch a layer react: TIME_WAIT sockets before and after 50 requests.ss -tan state time-wait | wc -lfor i in $(seq 50); do curl -s -o /dev/null http://localhost:8080/; doness -tan state time-wait | wc -l     # about 50 more: one per closed connection
Needs any small web server on port 8080. The side that closes first keeps TIME_WAIT. Read-only apart from the requests.

Debugging

Find the broken layer

Go bottom-up when nothing works, top-down when one app fails. Either way, ask one cheap question per layer and let each answer cut the search in half.

Ping works, the site does not

A working ping proves layers 1 to 3 for ICMP only. A firewall may still drop TCP 443.

Failures by layer

FailureSymptomCheck that tells it apartFix
Cable out, Wi-Fi offEverything fails, even the gatewayip -br link shows DOWN or NO-CARRIERReconnect, check the card
ARP failsGateway unreachable, link upip neigh shows FAILED or INCOMPLETESubnet mask, VLAN, the gateway itself
No route"Network is unreachable" at onceip route get IP errorsDefault route, DHCP
DNS broken"Could not resolve host"dig fails, curl --resolve with the IP worksResolver, record, search list
Port closed"Connection refused" at oncetcpdump shows SYN, then RSTStart the service, right port and address
Dropped by firewallHangs, then times outtcpdump shows SYNs repeating, no answerRule, security group, route back
Certificate expiredTLS error in curl or browsercurl -v shows the datesRenew, automate renewal
MTU black holeSmall requests work, big ones hangtracepath pmtu, ping -M do -s 1472Allow ICMP, lower MTU, clamp MSS
Backend down behind a proxyHTTP 502Proxy logs: upstream refused or resetFix or remove the backend
Backend slow behind a proxyHTTP 504Proxy logs: upstream timed outFind the slow call, tune timeouts
RFC 9110: 502 means a gateway got an invalid response from upstream, 503 means the server is overloaded or in maintenance, 504 means a gateway did not get a timely response.

Honest limits

Where the models are not true

Layers are a teaching tool, not a law. RFC 1122 already called strict layering imperfect, and RFC 3439 from 2002 has a section called "Layering Considered Harmful". Real systems cross the lines for speed or necessity:

Where layers help

  • Naming where a failure is
  • Swapping a link or app without touching the rest
  • Reading a capture header by header
  • Talking to other teams: "it's L4"

Where they blur

  • NAT and L4 load balancers rewrite ports from layer 3
  • TCP's checksum covers IP addresses
  • Path MTU discovery needs layer 3 to tell layer 4 a size
  • QUIC puts transport and TLS together in user space
  • Network cards do TCP segmentation in hardware

Summary

The whole topic in one minute.

OSI's seven layers are names; TCP/IP's four layers are what runs. Link moves frames to the next device by MAC address, internet moves packets across many networks by IP address, transport connects two programs by port, and the application gives the bytes meaning. Layers 5 and 6 of OSI live inside apps and libraries such as TLS.

On the way out each layer adds a header: 57 bytes of HTTP became a 79-byte TLS record, a 99-byte segment, a 119-byte packet and a 137-byte frame in our example. Switches read only layer 2, routers swap layer 2 and lower the TTL, NAT also rewrites addresses and ports, and the server takes the dolls apart in reverse order.

In production the layers are a map for failures. Ask the cheapest question for each layer: is the link up, is there a route and a neighbour, does the name resolve, does the TCP handshake finish, does TLS verify, what status does HTTP return. Then say which layer broke and why.

  • OSI's seven layers are the vocabulary; TCP/IP's four layers (link, internet, transport, application) are what runs.
  • Frame, packet, segment or datagram, message. MAC, IP, port, name.
  • Encapsulation: 57 bytes of HTTP became 79 (TLS), 99 (TCP), 119 (IP) and 137 (Ethernet with its check) in our example.
  • MTU 1500 minus 20 IP minus 20 TCP gives MSS 1460. The smallest Ethernet frame is 64 bytes.
  • ARP finds the next hop's MAC. Switches read L2, routers swap L2 and lower the TTL, NAT rewrites addresses and ports.
  • TCP: handshake, sequence numbers, retransmission, flow and congestion windows. UDP: 8 bytes and no promises.
  • Refused means RST, nothing listening. A timeout means something dropped the SYN.
  • Debug by layer with one command each: ip link, ip neigh, ip route get, dig, ss, curl -v, tcpdump.

Sources