Network Models: OSI vs TCP/IP, Encapsulation, What Happens When You Open a URL
"functions placed at low levels of a system may be redundant or of little value when compared with the cost of providing them at that low level." — Saltzer, Reed & Clark, End-to-End Arguments in System Design, 1984
Summary: A network is a stack of layers where each layer wraps the one above in its own header, so "open a URL" is really six or seven small protocols taking turns on the same bytes. Focus: OSI versus TCP/IP, encapsulation with real byte offsets, headers decoded field by field, the URL-to-pixels journey, where developers meet each layer (sockets, HTTP, Docker, Kubernetes, load balancers, VPNs), and the tools to see it all. Learning goal: Look at any networking problem and say which layer it lives in, which header carries the evidence, and which tool shows it.
This is the entry page of the ten-chapter networking group. It is the map: every later chapter (IP, NAT, DNS, ports, firewalls, Docker, Kubernetes, VPN, troubleshooting) is one region of the picture drawn here. It covers the models, the wrapping (encapsulation), the exact bytes of an Ethernet frame, an IPv4 header, a TCP SYN, a DNS query and an ARP request, the complete journey of one URL, and the commands that show each step on macOS and Linux. Protocol depth is not repeated here: for TCP versus UDP behaviour read TCP & UDP, for HTTP/1.1, HTTP/2 and HTTP/3 read HTTP evolution, for balancing read Load balancing.
Page map
| If you are looking for | Go to |
|---|---|
| The ten networking chapters and what each owns | The networking group map |
| A table you can memorise in a minute | Everything in one minute |
| Why layers exist, and the three misunderstandings | Why layers exist |
| Where OSI, TCP/IP, RFC 1122 and the "5 layers" come from | Where the models come from |
| The seven OSI layers, which two are fiction | OSI, one layer at a time |
| The four/five-layer model and the mapping table | TCP/IP and the mapping |
| Wrapping, unwrapping, MTU, MSS, byte offsets | Encapsulation and decapsulation |
| Hex dumps of ARP, DNS, TCP SYN, an HTTP segment | Headers decoded from a capture |
| URL parse, DNS, TCP, TLS, HTTP, hops, NAT, render | What happens when you open a URL |
| MAC, IP, port, URL; frame, packet, segment | Addressing and PDU names |
| Switch, router, firewall, proxy, load balancer | Devices per layer |
| Sockets, Docker bridge, Kubernetes Service, VPN | Where developers meet each layer |
| End-to-end principle, middleboxes | The end-to-end principle |
| Propagation, serialization, queuing | Latency anatomy |
ip, ifconfig, ss, tcpdump, loopback | Interfaces and tools |
| Go and PHP code | Go, Laravel and PHP |
| Reproduce it on your laptop | Lab |
The networking group map
| # | Chapter | Mostly lives at | What it owns |
|---|---|---|---|
| 1 | Network Models (this page) | all layers | The map, encapsulation, the URL journey, tool basics |
| 2 | IP addressing, subnets, CIDR | L3 (and ARP at L2) | IPv4/IPv6, private ranges, subnet math, gateways, routing tables, ARP/NDP |
| 3 | NAT, DHCP, port forwarding | L3/L4 | PAT, DHCP lease flow, CGNAT, hairpin NAT |
| 4 | DNS resolution | L7 | Resolvers, records, TTL, /etc/hosts, resolv.conf, split DNS |
| 5 | Ports, sockets, connections | L4 | Ephemeral ports, TIME_WAIT, keepalive, backlog, conntrack |
| 6 | Firewalls | L3/L4 | iptables, nftables, security groups, NACLs, egress control |
| 7 | Docker networking | L2/L3 | bridge, host, overlay, macvlan, published ports, MTU |
| 8 | Kubernetes networking | L3/L4/L7 | CNI, Services, kube-proxy, CoreDNS, Ingress, NetworkPolicy |
| 9 | VPNs and tunnels | L3 over L4 | SSH forwarding, bastions, WireGuard, zero-trust access |
| 10 | Troubleshooting playbook | all layers | Refused vs timeout, DNS failures, MTU, conntrack, captures |
TLS sits just before this group in TLS in practice; authoritative DNS design is in IP, DNS, GeoDNS.
Everything in one minute
The stack. Every row is unpacked later.
| Layer (OSI number) | TCP/IP name | Unit (PDU) | Address | Typical protocols | Device that cares | Where you meet it |
|---|---|---|---|---|---|---|
| 7 Application | Application | message / data | URL, host name | HTTP, DNS, SMTP, gRPC | L7 proxy, WAF | fetch, curl, HTTP clients |
| 6 Presentation | Application | data | media type, charset | TLS records, JSON, UTF-8 | (none, done inside the app) | Content-Type, encodings |
| 5 Session | Application | data | session id, cookie | RPC sessions, TLS resumption | (none) | Cookies, tokens |
| 4 Transport | Transport | segment (TCP), datagram (UDP) | port | TCP, UDP, QUIC | L4 load balancer, firewall, NAT | Sockets, ss, nc |
| 3 Network | Internet | packet | IP address | IPv4, IPv6, ICMP | router, L3 firewall | ip route, ping, VPN |
| 2 Data link | Link | frame | MAC address | Ethernet, Wi-Fi, ARP | switch, bridge | ip link, Docker bridge |
| 1 Physical | Link | bits | (none) | copper, fibre, radio | hub, repeater, cable | Link light, ethtool |
The wrapping, in bytes (one GET, 56 bytes of text):
| Step | Header added | Size | Running total |
|---|---|---|---|
| HTTP text | (none) | 56 | 56 |
| + TCP | source port, destination port, seq, ack, flags | 20 (up to 60 with options) | 76 |
| + IPv4 | source IP, destination IP, TTL, protocol | 20 (up to 60 with options) | 96 |
| + Ethernet | destination MAC, source MAC, EtherType | 14 | 110 |
| (+ FCS) | CRC-32 trailer, stripped by the NIC before tcpdump sees it | 4 | 114 on the wire |
The numbers to remember.
| Number | Meaning |
|---|---|
| 1500 | Ethernet MTU: largest IP packet one frame carries |
| 1460 | TCP MSS on Ethernet: 1500 - 20 (IP) - 20 (TCP) |
| 14 / 20 / 20 | Ethernet / IPv4 / TCP base header sizes |
| 8 | UDP header size |
| 64 | Default IP TTL on Linux and macOS |
| 0x0800 / 0x0806 / 0x86DD | EtherType: IPv4 / ARP / IPv6 |
| 6 / 17 / 1 | IP protocol numbers: TCP / UDP / ICMP |
| 80 / 443 / 53 | HTTP / HTTPS / DNS ports |
Why layers exist
A network has to get bytes between two programs on two machines across cables, radios, routers and other people's equipment. No single design can do all of that. Layers split the job so each part can change independently: Wi-Fi replaced Ethernet cables without touching HTTP, and HTTP/3 replaced TCP with QUIC without touching Ethernet.
Everyday analogy (reused through the page): sending a letter inside a letter. You write a message (HTTP). You put it into an envelope addressed to a person at a building (TCP: which person inside the building, which is the port). The building's address goes on an outer envelope for the postal system (IP: which building in the world). The postal truck gets a delivery slip for the next depot only (Ethernet: which neighbour handles it next). At every depot the slip is thrown away and a new one is written; the inner envelopes are never opened.
| Without layers | With layers |
|---|---|
| One giant protocol; every change touches everything | Each layer talks only to the layer above and below |
| Applications must know about cables and radios | Applications open a socket and write bytes |
| One vendor owns the whole stack | Many vendors per layer interoperate (a switch from one, a router from another) |
| Debugging means guessing | Debugging means finding the layer, then its header |
Three misunderstandings, up front.
| Belief | Reality |
|---|---|
| "The internet runs on the seven OSI layers" | The internet runs on TCP/IP, designed before OSI was finished. OSI is a teaching vocabulary; layers 5 and 6 have no separate software in practice |
| "My request goes straight to the server" | It is re-framed at every hop: a new Ethernet header per hop, the same IP packet end to end (until NAT rewrites it) |
| "IP address = identity of the machine" | An IP names an interface at a point in the network, changes with DHCP, is shared by many hosts behind NAT; a MAC is only meaningful on one link |
Where the models come from
The Internet suite (IP, TCP, UDP) was specified in the late 1970s and 1980s. RFC 791 defines IP, RFC 768 UDP, and RFC 9293 (2022) is the current TCP specification, replacing RFC 793. The IETF wrote the layering down in RFC 1122, "Requirements for Internet Hosts - Communication Layers" (1989), which names four layers: link, internet, transport, application. The ISO Open Systems Interconnection reference model (ISO 7498, 1984) defines seven. OSI protocols themselves lost the market; the OSI vocabulary survived because "layer 2", "layer 4" and "layer 7" are convenient labels.
| Source | What it says | Used here for |
|---|---|---|
| RFC 1122 (1989) | Four layers; the application layer "essentially combines the functions of the top two layers -- Presentation and Application -- of the OSI reference model" | Why OSI 5/6 are folded away |
| RFC 791 (1981) | IPv4 header format, IHL in 32-bit words | Byte offsets |
| RFC 9293 (2022) | TCP header, MSS option, default send MSS 536 for IPv4 when no option arrives | MSS and the SYN options |
| RFC 826 | ARP packet layout (hardware type, protocol type, opcode) | ARP dump |
| RFC 1035 | DNS header and question format, UDP messages 512 octets or less | DNS dump |
| RFC 3986 | URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] | URL parsing |
| RFC 3234 | A middlebox is "any intermediary device performing functions other than the normal, standard functions of an IP router on the datagram path" | Middleboxes |
| RFC 3439 | "Layering Considered Harmful": strict layering hides information that lower layers need to optimise | Why real stacks cheat |
| Saltzer et al. 1984 | The end-to-end argument | End-to-end section |
| Docker docs, Kubernetes docs, WireGuard site | Bridge = software bridge; Service = virtual IP via kube-proxy; WireGuard "securely encapsulates IP packets over UDP" | Developer touch-points |
A note on honesty: ISO 7498 itself is not freely available, so the OSI layer descriptions below are taken from the IETF documents that discuss the mapping (RFC 1122) and are marked as the common teaching summary, not quoted from the ISO text.
The concept catalogue
OSI, one layer at a time
Must-knowIn plain words: OSI cuts the job into seven jobs, numbered from the cable (1) up to the program (7). Use the numbers as nicknames: "layer 2 problem" means "a problem between two devices on the same link".
Common misunderstanding: "Every real network stack has seven separate layers and each packet goes through seven steps." No. In real stacks layers 5, 6 and 7 are the same code in your application (a TLS library and an HTTP library), and layers 1 and 2 are the NIC driver. The model is a vocabulary, not an architecture diagram.
Definition: the Open Systems Interconnection model partitions communication functions into seven layers, each providing services to the one above and using services from the one below.
| # | Layer | What it really contains | Real-world protocols | Fiction level |
|---|---|---|---|---|
| 7 | Application | The protocols programs speak: requests, methods, records | HTTP, DNS, SMTP, IMAP, SSH, gRPC, MQTT | Real |
| 6 | Presentation | Encoding, compression, encryption, serialization | TLS records, UTF-8, JSON, Protobuf, gzip | Fiction: done by libraries inside the app |
| 5 | Session | Dialog control, checkpoints, resumption | Cookies, TLS session tickets, RPC session ids, NetBIOS/RPC historic | Fiction: no separate layer in TCP/IP |
| 4 | Transport | Ports, reliability, ordering, flow and congestion control | TCP, UDP, QUIC, SCTP | Real |
| 3 | Network | Addressing and routing between networks | IPv4, IPv6, ICMP, IPsec, GRE | Real |
| 2 | Data link | Framing and addressing on one link, MAC | Ethernet (802.3), Wi-Fi (802.11), ARP, VLAN (802.1Q), PPP | Real (split into MAC and LLC in IEEE 802, rarely mentioned) |
| 1 | Physical | Signals: voltage, light, radio, connectors | 1000BASE-T, fibre, 802.11 radio | Real, but not software |
Two practical remarks. TLS is the classic argument: it encrypts (presentation), keeps a session with resumption tickets (session), and runs on TCP between the application and the socket, so it is labelled "layer 5", "6" or "4.5" depending on who you ask. ARP is the second: it carries IP addresses (layer 3 information) in a layer 2 frame and has its own EtherType, so it belongs to neither layer cleanly. Both are a signal to stop arguing about labels and look at the bytes.
TCP/IP and the mapping
Must-knowIn plain words: The Internet model has four layers: link, internet, transport, application. Many textbooks split link into physical and data link to give five.
Common misunderstanding: "TCP/IP means only TCP and IP." The name stands for the whole suite: IP, ICMP, ARP-adjacent link glue, TCP, UDP, DNS, HTTP and everything above.
Definition: RFC 1122 defines the layers by the interface they offer: the link layer moves a frame across one network; the internet layer moves a datagram across networks; the transport layer gives process-to-process delivery; the application layer is everything above.
| OSI (7) | 5-layer teaching model | TCP/IP RFC 1122 (4) | Example you can see | Linux/macOS object |
|---|---|---|---|---|
| 7, 6, 5 | 5 Application | Application | GET / HTTP/1.1, DNS question | the process |
| 4 | 4 Transport | Transport | TCP SYN, UDP datagram, ports | socket, ss, netstat |
| 3 | 3 Network | Internet | IPv4 header, TTL, routing | routing table, ip route |
| 2 | 2 Data link | Link | Ethernet header, ARP | interface, neighbour table |
| 1 | 1 Physical | Link | link light, radio | NIC, ethtool |
Everything above layer 4 is the application's business. That is why a Go or PHP program calls connect() once and then only writes bytes: the kernel owns layers 4, 3 and 2 (down to the driver).
Encapsulation and decapsulation
Must-knowIn plain words: On the way down the stack each layer puts its own header in front of the data it was handed. On the way up each layer strips its own header and hands the rest upward. The headers are the layer's private notes to the same layer on the other side.
Common misunderstanding: "A router reads my whole HTTP request." A router reads the Ethernet header (then discards it) and the IP header. It never needs ports, and it does not look at the payload. Firewalls and NAT boxes that read ports, and proxies that read HTTP, are doing extra work on purpose.
Definition: encapsulation wraps a layer's protocol data unit (PDU) as the payload of the next lower layer's PDU; decapsulation reverses it. The payload of layer N is the whole PDU of layer N+1.
sender receiver
HTTP GET / HTTP/1.1 ... (56 bytes) HTTP GET / HTTP/1.1 ...
| + TCP header (20) ports 51234 -> 80, seq, ack, flags ^ strip TCP, deliver bytes to the socket
TCP segment (76) |
| + IPv4 header (20) 10.84.50.174 -> 104.20.23.154, TTL 64 ^ strip IPv4, check protocol = 6
IP packet (96) |
| + Ethernet header (14) dst MAC, src MAC, EtherType 0x0800 ^ strip Ethernet, check dst MAC = mine
Ethernet frame (110) ----> NIC adds preamble and 4-byte FCS ------> frame (110) after the NIC verified the FCSMTU, MSS, fragmentation. The MTU (maximum transmission unit) is the largest IP packet a link carries; on Ethernet it is 1500 bytes of IP packet (the frame is 14 bytes larger, plus 4 for FCS). The MSS (maximum segment size) is the largest TCP payload: 1500 - 20 - 20 = 1460. Each side announces its MSS in the SYN (mss 1460). If a router must forward a packet larger than the next link's MTU and the DF (don't fragment) bit is set, it drops the packet and sends back ICMP "Fragmentation needed" (type 3, code 4) so the sender can lower its size; this is Path MTU Discovery (RFC 1191). If those ICMP messages are filtered, big packets vanish silently while small ones pass: the classic "SSH works but scp hangs" symptom, covered in the troubleshooting playbook.
| Item | Value | Where it is set |
|---|---|---|
| Ethernet II header | 14 bytes (6 + 6 + 2) | Link layer |
| Ethernet payload | 46 to 1500 bytes (padded to 46 if shorter, per RFC 894) | Link layer |
| Ethernet FCS | 4 bytes | NIC hardware |
| IPv4 header | 20 bytes without options, up to 60 | IHL field, in 32-bit words |
| TCP header | 20 bytes without options, up to 60 | Data Offset field, in 32-bit words |
| UDP header | 8 bytes | fixed |
| MSS on Ethernet/IPv4 | 1460 | TCP option in SYN |
| Default MSS if no option arrives | 536 (576 - 40), IPv4 | RFC 9293 |
macOS net.inet.tcp.mssdflt | 512 (measured on this machine) | sysctl |
| Loopback MTU | 16384 on macOS lo0 (measured), 65536 on Linux lo | interface |
| VPN/tunnel MTU | 4064 on macOS utun4 here; WireGuard typically 1420 | interface |
Headers decoded from a capture
Must-knowIn plain words: A packet is just a list of numbers. Once you know the offsets you can read it with your eyes.
Common misunderstanding: "Packet captures are unreadable noise." The first 54 bytes of almost every frame you will ever see (14 + 20 + 20) always have the same shape.
Definition: a capture is a file of timestamped frames; tcpdump -XX prints each frame as hex plus ASCII, -e prints the Ethernet header, -nn stops name and service lookups.
How the captures on this page were produced. The page's five frames were built byte by byte by the Go program frames/main.go using real values from this machine (its MAC, its Wi-Fi IP 10.84.50.174, its gateway 10.84.50.254, example.com at 104.20.23.154), written to a pcap file, and decoded by the system tcpdump -r (which does not need root to read a file). tcpdump independently verified the IP and TCP/UDP checksums as correct. Live capture on a real interface needs root (/dev/bpf* on macOS, CAP_NET_RAW on Linux); this documentation was written without root, so the frames are reconstructions with the exact layout a live capture shows, not live captures. The lab shows the live commands. Timestamps appear as 00:10:00 because tcpdump prints local time (UTC+03:30).
$ tcpdump -r frames.pcap -nn
reading from file frames.pcap, link-type EN10MB (Ethernet)
00:10:00.000000 ARP, Request who-has 10.84.50.254 tell 10.84.50.174, length 28
00:10:00.003000 ARP, Reply 10.84.50.254 is-at 56:ba:6d:ec:d8:fe, length 28
00:10:00.006000 IP 10.84.50.174.53124 > 10.84.50.254.53: 14971+ A? example.com. (29)
00:10:00.009000 IP 10.84.50.174.51234 > 104.20.23.154.80: Flags [S], seq 439041101, win 64240, options [mss 1460,sackOK,nop,wscale 7,nop,nop], length 0
00:10:00.012000 IP 10.84.50.174.51234 > 104.20.23.154.80: Flags [P.], seq 439041102:439041158, ack 2676915565, win 64240, length 56: HTTP: GET / HTTP/1.1Frame 1: ARP request (42 bytes)
$ tcpdump -r frames.pcap -nn -e -XX 'arp'
e6:22:8e:ba:6e:f0 > ff:ff:ff:ff:ff:ff, ethertype ARP (0x0806), length 42: Request who-has 10.84.50.254 tell 10.84.50.174, length 28
0x0000: ffff ffff ffff e622 8eba 6ef0 0806 0001 ......."..n.....
0x0010: 0800 0604 0001 e622 8eba 6ef0 0a54 32ae ......."..n..T2.
0x0020: 0000 0000 0000 0a54 32fe .......T2.| Offset | Bytes | Field | Meaning |
|---|---|---|---|
| 0-5 | ff ff ff ff ff ff | Ethernet destination | Broadcast: every host on the link reads it |
| 6-11 | e6 22 8e ba 6e f0 | Ethernet source | My Wi-Fi MAC (a locally administered, randomised address) |
| 12-13 | 08 06 | EtherType | ARP |
| 14-15 | 00 01 | Hardware type | Ethernet |
| 16-17 | 08 00 | Protocol type | IPv4 (same value as the EtherType for IP) |
| 18 | 06 | Hardware size | 6 bytes per MAC |
| 19 | 04 | Protocol size | 4 bytes per IPv4 address |
| 20-21 | 00 01 | Opcode | 1 = request, 2 = reply |
| 22-27 | e6 22 8e ba 6e f0 | Sender MAC | Me |
| 28-31 | 0a 54 32 ae | Sender IP | 10.84.50.174 |
| 32-37 | 00 00 00 00 00 00 | Target MAC | Unknown, that is the question |
| 38-41 | 0a 54 32 fe | Target IP | 10.84.50.254, the default gateway |
The reply (frame 2) has opcode 00 02, the gateway's MAC 56:ba:6d:ec:d8:fe as sender MAC and is sent unicast. On the wire the frame is padded to 60 bytes (46-byte minimum payload) plus FCS; many captures show 42 because the NIC adds the padding. This is why IP never "knows" a MAC: ARP (IPv4) and NDP (IPv6) translate IP to MAC per link; the result is cached (arp -an, ip neigh).
Frame 3: DNS query over UDP (71 bytes)
$ tcpdump -r frames.pcap -nn -e -vv -XX 'udp port 53'
e6:22:8e:ba:6e:f0 > 56:ba:6d:ec:d8:fe, ethertype IPv4 (0x0800), length 71: (tos 0x0, ttl 64, id 7238, offset 0, flags [DF], proto UDP (17), length 57)
10.84.50.174.53124 > 10.84.50.254.53: [udp sum ok] 14971+ A? example.com. (29)
0x0000: 56ba 6dec d8fe e622 8eba 6ef0 0800 4500 V.m...."..n...E.
0x0010: 0039 1c46 4000 4011 a41a 0a54 32ae 0a54 .9.F@.@....T2..T
0x0020: 32fe cf84 0035 0025 abad 3a7b 0100 0001 2....5.%..:{....
0x0030: 0000 0000 0000 0765 7861 6d70 6c65 0363 .......example.c
0x0040: 6f6d 0000 0100 01 om.....| Offset | Bytes | Layer / field | Meaning |
|---|---|---|---|
| 0-5 | 56 ba 6d ec d8 fe | Ethernet dst | The gateway's MAC, not the DNS server's: the next hop |
| 6-11 | e6 22 8e ba 6e f0 | Ethernet src | Me |
| 12-13 | 08 00 | EtherType | IPv4 |
| 14 | 45 | IP version + IHL | Version 4, IHL 5 words = 20 bytes |
| 15 | 00 | IP DSCP/ECN | Best effort |
| 16-17 | 00 39 | IP total length | 57 = 20 IP + 8 UDP + 29 DNS |
| 18-19 | 1c 46 | IP identification | 7238 |
| 20-21 | 40 00 | Flags + fragment offset | DF set, offset 0 |
| 22 | 40 | TTL | 64 |
| 23 | 11 | Protocol | 17 = UDP |
| 24-25 | a4 1a | IP header checksum | Verified by tcpdump |
| 26-29 | 0a 54 32 ae | Source IP | 10.84.50.174 |
| 30-33 | 0a 54 32 fe | Destination IP | 10.84.50.254 (the resolver) |
| 34-35 | cf 84 | UDP source port | 53124 (ephemeral) |
| 36-37 | 00 35 | UDP destination port | 53 |
| 38-39 | 00 25 | UDP length | 37 = 8 + 29 |
| 40-41 | ab ad | UDP checksum | Pseudo-header + segment |
| 42-43 | 3a 7b | DNS transaction id | 14971 (matches the reply) |
| 44-45 | 01 00 | DNS flags | RD = recursion desired |
| 46-47 | 00 01 | QDCOUNT | One question |
| 48-53 | 00 00 00 00 00 00 | ANCOUNT, NSCOUNT, ARCOUNT | Zero in a query |
| 54-66 | 07 example 03 com 00 | QNAME | Length-prefixed labels, ended by a zero byte |
| 67-68 | 00 01 | QTYPE | A (IPv4 address) |
| 69-70 | 00 01 | QCLASS | IN (Internet) |
RFC 1035 sets UDP DNS messages at 512 octets or less (larger answers use EDNS0 or retry over TCP). The destination here is the gateway's IP and the gateway's MAC at once: the resolver is on the same subnet, so no router rewrite is needed.
Frame 4: TCP SYN (66 bytes)
$ tcpdump -r frames.pcap -nn -e -vv -XX 'tcp[tcpflags] & tcp-syn != 0'
e6:22:8e:ba:6e:f0 > 56:ba:6d:ec:d8:fe, ethertype IPv4 (0x0800), length 66: (tos 0x0, ttl 64, id 7239, offset 0, flags [DF], proto TCP (6), length 52)
10.84.50.174.51234 > 104.20.23.154.80: Flags [S], cksum 0x9885 (correct), seq 439041101, win 64240, options [mss 1460,sackOK,nop,wscale 7,nop,nop], length 0
0x0000: 56ba 6dec d8fe e622 8eba 6ef0 0800 4500 V.m...."..n...E.
0x0010: 0034 1c47 4000 4006 61cd 0a54 32ae 6814 .4.G@.@.a..T2.h.
0x0020: 179a c822 0050 1a2b 3c4d 0000 0000 8002 ...".P.+<M......
0x0030: faf0 9885 0000 0204 05b4 0402 0103 0307 ................
0x0040: 0101 ..| Offset | Bytes | Field | Meaning |
|---|---|---|---|
| 0-13 | 56ba6decd8fe e6228eba6ef0 0800 | Ethernet | To the gateway MAC, IPv4 inside |
| 14 | 45 | IP version/IHL | 20-byte header |
| 16-17 | 00 34 | Total length | 52 = 20 IP + 32 TCP |
| 22 | 40 | TTL | 64 |
| 23 | 06 | Protocol | 6 = TCP |
| 26-29 | 0a 54 32 ae | Source IP | Me |
| 30-33 | 68 14 17 9a | Destination IP | 104.20.23.154 (a public address: the gateway MAC is used, the IP stays) |
| 34-35 | c8 22 | Source port | 51234 |
| 36-37 | 00 50 | Destination port | 80 |
| 38-41 | 1a 2b 3c 4d | Sequence number | 439041101: the ISN (initial sequence number) |
| 42-45 | 00 00 00 00 | Acknowledgment | 0, no ACK flag yet |
| 46 | 80 | Data offset (high nibble) | 8 words = 32 bytes: 20 base + 12 of options |
| 47 | 02 | Flags | SYN (0x02). Others: FIN 0x01, RST 0x04, PSH 0x08, ACK 0x10, URG 0x20 |
| 48-49 | fa f0 | Window | 64240 |
| 50-51 | 98 85 | TCP checksum | Pseudo-header + segment |
| 52-53 | 00 00 | Urgent pointer | Unused |
| 54-57 | 02 04 05 b4 | Option MSS | kind 2, length 4, value 1460 |
| 58-59 | 04 02 | Option SACK permitted | kind 4, length 2 |
| 60 | 01 | NOP | Padding |
| 61-63 | 03 03 07 | Option window scale | kind 3, length 3, shift 7 (window x 128) |
| 64-65 | 01 01 | NOP NOP | Pad to a 4-byte boundary |
Real Linux SYNs also carry the timestamp option (kind 8, 10 bytes) and use 60 bytes of TCP header; here the option list is shortened. The three-way handshake is SYN (seq x) then SYN/ACK (seq y, ack x+1) then ACK (ack y+1). The SYN consumes one sequence number, which is why the first data byte of the next frame has seq 439041102.
Frame 5: an HTTP request segment (110 bytes)
$ tcpdump -r frames.pcap -nn -XX 'tcp and greater 100'
0x0000: 56ba 6dec d8fe e622 8eba 6ef0 0800 4500 V.m...."..n...E.
0x0010: 0060 1c48 4000 4006 61a0 0a54 32ae 6814 .`.H@.@.a..T2.h.
0x0020: 179a c822 0050 1a2b 3c4e 9f8e 7d6d 5018 ...".P.+<N..}mP.
0x0030: faf0 49f2 0000 4745 5420 2f20 4854 5450 ..I...GET./.HTTP
0x0040: 2f31 2e31 0d0a 486f 7374 3a20 6578 616d /1.1..Host:.exam
0x0050: 706c 652e 636f 6d0d 0a43 6f6e 6e65 6374 ple.com..Connect
0x0060: 696f 6e3a 2063 6c6f 7365 0d0a 0d0a ion:.close....| Offset | Bytes | Field | Meaning |
|---|---|---|---|
| 0-13 | Ethernet | 14 bytes | Same MACs as the SYN |
| 14-33 | IPv4 | 20 bytes | Total length 00 60 = 96 = 20 + 20 + 56 |
| 34-53 | TCP | 20 bytes | Data offset 50 = 5 words = 20 bytes, no options |
| 38-41 | 1a 2b 3c 4e | Sequence | 439041102 = ISN + 1 |
| 42-45 | 9f 8e 7d 6d | Acknowledgment | The server's ISN + 1 |
| 47 | 18 | Flags | PSH (0x08) + ACK (0x10): push this data, acknowledgment valid |
| 54-109 | 47 45 54 20 2f ... | HTTP payload | ASCII GET / HTTP/1.1 CR LF Host: example.com CR LF Connection: close CR LF CR LF: 56 bytes |
Everything from offset 54 on is layer 7: the bytes 0d 0a (CR LF) end each header line and 0d 0a 0d 0a ends the request header section. The same field offsets are parsed by decode/main.go and by gopacket in gopacketdump/main.go.
What happens when you open a URL
Must-knowIn plain words: You type an address; your computer finds out where that name lives, opens a connection, optionally encrypts it, asks for the page, gets bytes back and draws them. Each step is one layer's job.
Common misunderstanding: "The browser sends the request to the domain." There is no such thing as sending to a domain. The domain is turned into an IP address first (DNS); only the IP address and a port are used to build packets.
Definition: the URL journey is the ordered set of protocol exchanges between typing http://example.com/ and the first rendered pixel: parse, resolve, connect, secure, request, respond, render.
| Step | Layer | What happens | Evidence you can see | Typical cost |
|---|---|---|---|---|
| 0 Parse | 7 | Split scheme, host, port, path, query, fragment (RFC 3986). Default port from the scheme (http 80, https 443). The fragment never leaves the browser | url.Parse in Go, parse_url() in PHP | microseconds |
| 1 Local lookups | 7 | Browser DNS cache, OS cache, /etc/hosts | scutil --dns, cat /etc/hosts | 0 ms on a hit |
| 2 DNS query | 7 over 4 | The stub resolver asks the configured recursive resolver (UDP 53); on a miss the resolver walks root, TLD and authoritative servers and caches the answer for the record's TTL | dig example.com, tcpdump udp port 53 | 0-100 ms+ |
| 3 Route decision | 3 | The kernel picks the interface and next hop from the routing table: on-link destination uses its own MAC, anything else uses the default gateway | route -n get, ip route get | microseconds |
| 4 ARP | 2 | Find the next hop's MAC if not cached | arp -an, ip neigh | 1 LAN RTT, once |
| 5 TCP handshake | 4 | SYN, SYN/ACK, ACK; connect() returns after one RTT | tcpdump 'tcp[tcpflags] & tcp-syn != 0', curl -w %{time_connect} | 1 RTT |
| 6 TLS (https only) | 4.5 / 6 | ClientHello, ServerHello, certificate, Finished; TLS 1.3 adds 1 RTT, TLS 1.2 adds 2 RTT | openssl s_client, TLS in practice | 1-2 RTT |
| 7 HTTP request | 7 | GET / HTTP/1.1, Host: header selects the site | curl -v, nc | RTT/2 to reach the server |
| 8 Server work | 7 | App code, database, templates | time_starttransfer - time_connect | whatever your code costs |
| 9 Response | 7 / 4 | Headers, then body in many segments; TCP slow start limits the first flights | curl -w %{time_total} | 1 RTT + transfer |
| 10 Render | 7 | Parse HTML, discover CSS/JS/images, repeat steps 1-9 per origin (reuse connections when possible) | browser DevTools Network tab | tens to thousands of ms |
Between steps 5 and 9 every packet crosses routers. At each hop the Ethernet header is replaced, the IP TTL drops by one, and the IP addresses stay as they are, until a NAT box at the edge rewrites them:
hop L2 (changes every hop) L3 (stays) L4 (stays unless NAT/PAT)
laptop src e6:22.. -> dst 56:ba.. (gw) 10.84.50.174 -> 104.20.23.154 ttl 64 51234 -> 80
home router (new frame, ISP side MACs) same, ttl 63, then NAT rewrites: src becomes 203.0.113.9:40001
203.0.113.9 -> 104.20.23.154
ISP routers new frame per hop 203.0.113.9 -> 104.20.23.154, ttl-- 40001 -> 80
server last-hop MACs arrives with the NAT address replies to 203.0.113.9:40001(The 203.0.113.0/24 address is a documentation range, standing in for the home router's public address.) traceroute exploits the TTL: it sends probes with TTL 1, 2, 3... and each router that drops one to zero answers with ICMP "time exceeded" (this machine's real output toward 104.20.23.154: hop 1 10.84.50.254, 7.5 ms; hop 2 silent; hop 3 10.222.211.65, 138.7 ms). NAT and DHCP are in NAT, DHCP, port forwarding; routing tables and ARP in IP addressing.
A real surprise on this machine. The Mac used to write this page runs a TUN-mode proxy: route -n get example.com shows interface: utun4, DNS returns a "fake IP" (198.18.1.39, from the benchmarking range 198.18.0.0/15) and the TCP handshake "completes" in 0.3 ms because a local process answers, not the real server. Binding the source address to the Wi-Fi interface (curl --interface en0 --resolve example.com:80:104.20.23.154) took the real path: handshake 117 ms to 2.8 s over three tries on this unstable link, 158 ms in an earlier run. The lesson is the end-to-end principle in action: a middlebox can make a connection look healthier or different than the path behind it.
Addressing and PDU names
Must-knowIn plain words: Each layer has its own kind of address, and each address is only meaningful at its own layer.
Common misunderstanding: "I can use the MAC address to reach a server on the internet." A MAC is rewritten at every hop and only works on one link; routers drop it. The IP address is the end-to-end address; the port picks the program.
| Layer | Address | Example | Size | Scope | Who assigns it | Changes at each hop? |
|---|---|---|---|---|---|---|
| 7 | URL / host name | http://example.com/a?b=1 | text | global | the site owner, DNS | no |
| 4 | Port | 80, 51234 | 16 bits | one host | service (well-known) or kernel (ephemeral) | no (unless PAT rewrites it) |
| 3 | IPv4 address | 104.20.23.154 | 32 bits | global (or private) | operator, DHCP, ISP | no (unless NAT rewrites it) |
| 3 | IPv6 address | 2606:4700::6814:179a | 128 bits | global or link-local | SLAAC, DHCPv6, operator | no |
| 2 | MAC address | 56:ba:6d:ec:d8:fe | 48 bits | one link | NIC vendor (or randomised) | yes, every hop |
| Layer | PDU name | Header | Maximum |
|---|---|---|---|
| 7 | message, data, request/response | protocol specific | unlimited (streams) |
| 4 TCP | segment | 20-60 bytes | MSS (1460) of payload per segment |
| 4 UDP | datagram | 8 bytes | 65507 payload bytes theoretical, in practice below the MTU |
| 3 | packet (IPv4 also "datagram") | 20-60 bytes | 65535 total, limited by the path MTU |
| 2 | frame | 14 bytes + 4 FCS | 1514 bytes without FCS (standard) |
| 1 | bit, symbol | none | n/a |
Words are used loosely in practice: people say "packet" for any of them. In this chapter, "frame" always means layer 2, "packet" layer 3, "segment" TCP.
Devices per layer
ImportantIn plain words: A device is named by the highest layer whose header it reads to decide what to do.
Common misunderstanding: "A switch and a router are the same box with different brand names." A switch forwards by destination MAC inside one network; a router forwards by destination IP between networks. Home "routers" bundle both, plus NAT, DHCP and Wi-Fi.
| Device | Layer | Reads | Decides by | Real-world example |
|---|---|---|---|---|
| Hub / repeater | 1 | nothing | repeats bits on all ports | obsolete |
| Switch / bridge | 2 | Ethernet dst MAC | MAC table (learns source MACs per port) | office switch, Linux bridge, Docker docker0 |
| Router | 3 | IP dst | longest-prefix match in the routing table | home router, AWS route table, Linux with ip_forward=1 |
| L3 switch | 2 + 3 | MAC and IP | both, in hardware | data-centre top-of-rack |
| Firewall (stateless, ACL) | 3 / 4 | IP and ports | rule list per packet | AWS network ACL |
| Firewall (stateful) | 3 / 4 | IP, ports, connection state | conntrack table | iptables, nftables, AWS security group |
| NAT gateway | 3 / 4 | IP and ports | rewrites addresses, tracks flows | home router, AWS NAT Gateway, Kubernetes egress |
| L4 load balancer | 4 | IP and port | picks a backend per connection | AWS NLB, HAProxy mode tcp, kube-proxy, IPVS |
| L7 proxy / load balancer | 7 | HTTP method, host, path, headers | routes per request | NGINX, Envoy, AWS ALB, Traefik, HAProxy mode http |
| WAF | 7 | HTTP content | rules over request content | Cloudflare WAF, ModSecurity |
| VPN gateway | 3 | IP | encapsulates IP in IP/UDP | WireGuard, IPsec |
Where developers meet each layer
Must-knowIn plain words: You rarely touch layers 1 to 3 directly, but each tool you use lives at one layer, so the layer tells you what it can and cannot see.
Common misunderstanding: "A Kubernetes Service is a process listening on a port." A ClusterIP Service is a virtual IP implemented as NAT rules (iptables or IPVS) on every node; no process listens on it.
| Thing you use | Layer | What it really is | What it cannot see |
|---|---|---|---|
net.Dial, fsockopen, socket() | 4 | A kernel socket: a TCP byte stream or UDP datagrams | HTTP, messages, framing |
| HTTP client / server, REST, GraphQL | 7 | Text or binary messages over a socket | MACs, routes, packet loss |
| gRPC | 7 over 4 | HTTP/2 frames carrying Protobuf | per-message routing at an L4 balancer |
| TLS | 4.5 / 6 | Records encrypted over a TCP stream | nothing on the wire except the SNI and sizes |
| Docker bridge network | 2 / 3 | A Linux software bridge (docker0), a veth pair per container, NAT for outbound traffic | HTTP |
Docker published port -p 8080:80 | 3 / 4 | A DNAT rule: host port 8080 to container IP port 80 | the request body |
| Kubernetes Service (ClusterIP) | 4 | Virtual IP and port, DNAT to a pod chosen per connection by kube-proxy | HTTP paths, headers |
| Kubernetes Ingress / Gateway | 7 | An HTTP reverse proxy (NGINX, Envoy) configured by objects | |
| Load balancer, L4 | 4 | Forwards connections or packets; backends see the same TCP bytes | which URL was requested |
| Load balancer, L7 | 7 | Terminates the client connection, opens a new one to a backend | nothing: it parses it all (costly) |
| VPN (WireGuard, IPsec) | 3 | A virtual interface (wg0, utun) that encapsulates IP packets inside UDP | application meaning |
SSH tunnel ssh -L | 4 over 7 | A TCP stream carried inside another TCP stream | |
ICMP ping | 3 | IP packets with protocol 1 (echo request/reply); no port | ports, services |
| CDN | 7 | Distributed HTTP caches reached via DNS or anycast | |
| Database connection | 4 / 7 | A long-lived TCP socket speaking the PostgreSQL/MySQL protocol |
PostgreSQL shows the L3/L4 identity of every session it serves, which is handy when a proxy or NAT sits in front:
-- What does the server think my address and ports are? (PostgreSQL)
SELECT inet_client_addr() AS client_ip, inet_client_port() AS client_port,
inet_server_addr() AS server_ip, inet_server_port() AS server_port;
-- Behind PgBouncer or a NAT you see the proxy's address, not the real client's.The functions are documented in the PostgreSQL "System Information Functions" page. See Connection pooling for what pools do at layer 4.
The end-to-end principle
ImportantIn plain words: Put the smart work (reliability, security, correctness checks) at the two ends of a conversation, and keep the middle simple. The middle cannot know what the application really needs.
Common misunderstanding: "If the network checks and retries, my app does not have to." Link-level checks (the Ethernet FCS) catch corrupted frames, but only an end-to-end check (TCP checksum plus the application's own checks) catches a bug in a router's memory or in a middlebox. That is Saltzer's original argument.
Definition: the end-to-end argument says a function can be completely and correctly implemented only with the knowledge and help of the application at the end points, so providing it inside the network is at best a performance enhancement. RFC 1958 adds fate-sharing: keep connection state in the endpoints so that it dies only when an endpoint dies.
Why middleboxes break things. RFC 3234 defines a middlebox as any intermediary doing more than the normal functions of an IP router. NAT, stateful firewalls, L7 proxies, TLS-inspecting appliances, WAN optimisers and TUN proxies all hold state or rewrite bytes the endpoints did not agree to.
| Middlebox | What it does | What it breaks | Symptom |
|---|---|---|---|
| NAT / PAT | Rewrites IPs and ports, keeps a flow table | Inbound connections, protocols that embed IPs (FTP active mode, SIP) | "works outbound, not inbound"; idle connections silently dropped after a timeout |
| Stateful firewall | Tracks flows, drops unknown ones | Long-idle connections, asymmetric routing | Connection hangs after minutes of silence |
| L7 proxy / CDN | Terminates and re-opens connections | Client IP visibility, WebSockets, long polls, Upgrade | App sees the proxy's IP; use X-Forwarded-For / PROXY protocol |
| Path MTU black hole | Drops ICMP "fragmentation needed" | Large packets only | Small requests fine, big uploads hang |
| TLS-inspecting box | Terminates TLS, re-signs | Certificate pinning, mTLS | Unknown CA errors |
| TUN-mode proxy (this machine) | Accepts the TCP handshake locally | Latency measurements, DNS truth | 0.3 ms "handshake" to a server 150 ms away |
| Carrier-grade NAT | Shares one public IP among subscribers | Port forwarding, peer-to-peer | You cannot open a port at home |
Each failure above is analysed in Network troubleshooting playbook; the proxy and load balancer designs are in Load balancing.
Latency anatomy per layer
ImportantIn plain words: The time for a packet to arrive has three physical parts: how long the signal travels, how long it takes to push the bits out, and how long it waits in line.
Common misunderstanding: "More bandwidth means lower latency." Bandwidth sets serialization time only. A 10 Gbit/s link between Tehran and Frankfurt still has the same propagation delay as a 10 Mbit/s one.
| Component | Layer | Formula | Typical size | How to reduce |
|---|---|---|---|---|
| Propagation delay | 1 | distance / signal speed (about 200,000 km/s in fibre, two-thirds of c) | 5 ms per 1000 km one way | Move the server closer (CDN, region) |
| Serialization delay | 1/2 | frame size / link rate | 1500 B on 100 Mbit/s = 120 us; on 1 Gbit/s = 12 us | Faster link |
| Queuing delay | 2/3 | time waiting in a router/switch buffer | 0 to hundreds of ms (bufferbloat) | Less load, AQM (CoDel, fq_codel) |
| Processing delay | 2/3 | lookup, firewall, NAT | microseconds | Hardware offload |
| Handshake cost | 4 | RTTs before data: TCP 1, TLS 1.3 +1 | 1 RTT each | Keep-alive, connection pools, TLS 1.3 0-RTT, HTTP/3 |
| DNS cost | 7 | 0 on cache, 1 RTT to the resolver, more on recursion | 0-200 ms | TTLs, local caches, dns-prefetch |
| Server time | 7 | application work | 1 ms to seconds | Your code |
total time to first byte (HTTP, new connection)
= DNS (0 or 1+ RTT) + TCP handshake (1 RTT) + [TLS (1 RTT)] + request travel (0.5 RTT) + server time + response travel (0.5 RTT)
this machine, via en0, example.com: tcp=158 ms ttfb=331 ms -> server + request/response = 173 msMeasured on this machine (macOS, Wi-Fi): ping to the gateway 4.0 / 5.7 / 7.8 ms min/avg/max (one hop, one link); ping -c 5 -S 10.84.50.174 104.20.23.154 min/avg/max 603 / 1172 / 1759 ms on a bad evening, an extreme example of queuing delay; loopback handshakes take 0.13 to 0.45 ms. TCP slow start then limits how much data the first round trips carry (TCP versus UDP behaviour is in TCP & UDP, connection reuse in HTTP evolution).
Interfaces and tools
Must-knowIn plain words: The OS gives you a handful of commands to list interfaces, addresses, routes, neighbours, sockets and packets. Linux and macOS use different tools for the same ideas.
Common misunderstanding: "ifconfig and netstat are the modern tools." On Linux they are deprecated (net-tools); ip and ss (iproute2) replace them. On macOS they are still the tools, because ip and ss do not exist there.
| Question | Linux (iproute2) | macOS | Notes |
|---|---|---|---|
| List interfaces and state | ip link | ifconfig -l, ifconfig | Both show MTU and MAC |
| Addresses | ip addr (ip -br a) | ifconfig en0, ipconfig getifaddr en0 | |
| Routing table | ip route, ip route get 8.8.8.8 | netstat -rn, route -n get 8.8.8.8 | ip route get shows interface, source and gateway chosen |
| Neighbour (ARP/NDP) cache | ip neigh | arp -an, ndp -an | |
| Sockets | ss -tulpn, ss -tan | netstat -an -p tcp, lsof -iTCP -sTCP:LISTEN -nP | ss is faster and shows timers and TCP info |
| Packet capture | tcpdump -i eth0, tcpdump -i any | tcpdump -i en0, one interface at a time | Needs root or CAP_NET_RAW / read access to /dev/bpf* |
| GUI capture | Wireshark, tshark | Wireshark (ChmodBPF helper) | |
| Reachability | ping, traceroute, mtr | ping, traceroute (BSD flags differ) | |
| DNS | dig, resolvectl status | dig, scutil --dns | |
| Per-connection timers | ss -ti | not available | RTT, cwnd, retransmits |
| Link statistics | ip -s link, ethtool -S eth0 | netstat -I en0, netstat -s |
Interface names
| Name | OS | Meaning |
|---|---|---|
lo / lo0 | Linux / macOS | Loopback, 127.0.0.1 and ::1; never leaves the machine |
eth0, ens5, enp3s0 | Linux | Ethernet; the second form is "predictable naming" by the udev rule (firmware index, PCI slot) |
wlan0, wlp2s0 | Linux | Wi-Fi |
en0, en1 | macOS | Ethernet or Wi-Fi (on this Mac en0 is Wi-Fi) |
docker0, br-3f2a... | Linux | Docker default and user-defined bridges |
veth1a2b3c | Linux | One end of a virtual Ethernet pair, the other end is eth0 inside a container |
cni0, flannel.1, cali*, cilium_* | Linux | Kubernetes CNI interfaces |
tun0, wg0 | Linux | Tunnel interfaces: OpenVPN, WireGuard |
utun0 ... utun4 | macOS | Tunnel interfaces for VPNs, iCloud Private Relay, proxies (this machine: utun4 is the default route) |
awdl0, llw0, ap1 | macOS | Apple Wireless Direct Link (AirDrop), low-latency WLAN, access point |
bridge0 | macOS | Thunderbolt/Internet-sharing bridge |
This machine's real data (macOS 27, Wi-Fi):
$ ifconfig en0
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether e6:22:8e:ba:6e:f0
inet6 fe80::1496:3daa:ddc1:3c65%en0 prefixlen 64 secured scopeid 0xc
inet 10.84.50.174 netmask 0xffffff00 broadcast 10.84.50.255
$ netstat -rn -f inet | head
default link#20 UCSg utun4 <- the TUN proxy is the primary default route
default 10.84.50.254 UGScIg en0 <- the real gateway
10.84.50/24 link#12 UCS en0 <- on-link subnet: use ARP, no gateway
$ arp -an
? (10.84.50.254) at 56:ba:6d:ec:d8:fe on en0 ifscope [ethernet]
$ ifconfig lo0 | head -1
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384The same checks on Linux (typical output, not captured on this machine):
$ ip -br a
lo UNKNOWN 127.0.0.1/8 ::1/128
eth0 UP 10.0.0.5/24 fe80::4001:aff:fe00:5/64
$ ip route get 104.20.23.154
104.20.23.154 via 10.0.0.1 dev eth0 src 10.0.0.5 uid 1000
$ ip neigh
10.0.0.1 dev eth0 lladdr 56:ba:6d:ec:d8:fe REACHABLE
$ ss -tan state established
Recv-Q Send-Q Local Address:Port Peer Address:Port
0 0 10.0.0.5:51234 104.20.23.154:80Loopback versus real interfaces
| Property | Loopback (lo, lo0) | Real NIC (eth0, en0) |
|---|---|---|
| Address | 127.0.0.0/8, ::1 | assigned (DHCP, static) |
| Layer 2 | none: no MAC, no ARP, no Ethernet header (BSD/macOS loopback captures use link type NULL, a 4-byte address-family header; a Linux lo capture shows an Ethernet header with zeroed MACs; stated from documentation knowledge, not verified here because capture needs root) | Ethernet or Wi-Fi |
| MTU | 16384 (macOS here), 65536 (Linux) | 1500 typical |
| Leaves the machine | never; the kernel hands the packet to itself | yes |
| Firewall | usually bypassed | applies |
| Bind effect | 127.0.0.1:8080 reachable only locally | 0.0.0.0:8080 reachable from the network |
| Misleading when | testing latency or MTU: 0.1 ms, no loss, no fragmentation |
A common bug: a container service bound to 127.0.0.1 is unreachable through a published port because the connection arrives on the container's eth0, not on its loopback. Bind 0.0.0.0 inside containers. See Docker networking and Ports, sockets and connections.
Mechanics
How the kernel builds a packet
When your program calls write() on a connected TCP socket, the kernel copies the bytes into the socket's send buffer, the TCP code cuts them into segments of at most the MSS, adds the TCP header, hands each segment to IP, which looks up the route, adds the IP header, finds the next hop's MAC from the neighbour cache, adds the Ethernet header and queues the frame for the NIC driver. On receive the NIC interrupts the kernel; the frame climbs the stack in reverse; the TCP code reassembles bytes into the receive buffer; read() returns them. Offloads (TSO, GSO, GRO, checksum offload) let the NIC do parts of this: on macOS ifconfig en0 shows options=6460<TSO4,TSO6,CHANNEL_IO,PARTIAL_CSUM,ZEROINVERT_CSUM>, and that is why a capture taken on the sending host can show frames larger than the MTU or checksum "incorrect": the NIC has not computed them yet.
1 app write(fd, "GET / ...", 56)
2 socket append to send buffer (SO_SNDBUF)
3 TCP segment: seq=ISN+1, ack=server ISN+1, flags PSH|ACK, checksum
4 IP route lookup: dst 104.20.23.154 -> via 10.84.50.254 dev en0, src 10.84.50.174
5 neigh next hop 10.84.50.254 -> MAC 56:ba:6d:ec:d8:fe (ARP cache hit)
6 Ethernet 14-byte header, EtherType 0x0800
7 driver DMA to the NIC; NIC appends FCS, sendsThe three-way handshake as a timeline
client server
1 SYN seq=x, mss=1460, wscale=7, SACK ok ----> LISTEN -> SYN_RCVD
2 SYN_SENT <---- SYN/ACK seq=y, ack=x+1, mss, wscale
3 ESTABLISHED ACK ack=y+1 ----> SYN_RCVD -> ESTABLISHED
4 PSH|ACK seq=x+1, 56 bytes of HTTP ---->
connect() returned after 1 RTT; accept() returned after step 3Checksums and where they live
| Layer | Check | Covers | Computed by |
|---|---|---|---|
| 2 | Ethernet FCS (CRC-32) | whole frame | NIC, stripped before capture |
| 3 | IPv4 header checksum | IP header only (IPv6 has none) | each router recomputes after TTL-1 |
| 4 | TCP / UDP checksum | pseudo-header + segment | end hosts |
| 7 | application (e.g. SHA-256 in downloads, TLS MACs) | payload | endpoints (the end-to-end argument) |
The checksum algorithm is the 16-bit ones-complement sum (RFC 1071), implemented in frames/main.go. See Checksums and hashing for the CRC family.
Error and status messages you will meet
| Message / symptom | Layer | Meaning |
|---|---|---|
No route to host (EHOSTUNREACH) | 3 / 2 | No route, or ARP got no answer |
Network is unreachable (ENETUNREACH) | 3 | No route matches, not even a default |
Connection refused (ECONNREFUSED) | 4 | A RST came back: host reachable, nothing listening (or firewall REJECT) |
Connection timed out (ETIMEDOUT) | 3 / 4 | No reply at all: dropped by a firewall, wrong IP, or host down |
Connection reset by peer (ECONNRESET) | 4 | RST in the middle of a connection |
Name or service not known / Could not resolve host | 7 (DNS) | The resolver returned NXDOMAIN or failed |
| ICMP type 3 code 4 | 3 | Fragmentation needed and DF set (Path MTU) |
| ICMP type 11 | 3 | TTL exceeded in transit (traceroute) |
| HTTP 502 / 504 | 7 | A proxy could not reach or wait for the upstream |
Solving the classic problems
| Problem | Layer | Fast diagnosis | Fix |
|---|---|---|---|
| "Site does not load" | any | ping IP, dig name, curl -v in that order | The first failing step names the layer |
| Name resolves wrong or slow | 7 | dig +trace, scutil --dns / resolvectl status | Fix the resolver, TTL or /etc/hosts |
| Connection refused | 4 | ss -tlnp, lsof -iTCP -sTCP:LISTEN | Start the service, bind the right address, open the port |
| Connection timeout | 3/4 | traceroute, tcpdump shows SYNs with no SYN/ACK | Firewall, security group, route |
| Large transfers hang, small ones work | 3 | ping -D -s 1472 | Fix MTU/MSS clamping, allow ICMP type 3 |
| Container cannot reach another | 2/3 | ip addr, ip route inside; docker network inspect | Same network, correct name |
| Works on localhost, not remotely | 4 | ss -tln shows 127.0.0.1:port | Bind 0.0.0.0 |
| Client IP is always the proxy | 3/7 | log X-Forwarded-For | Trust the header from known proxies; PROXY protocol for L4 |
Reading a capture the right way
- Start with
tcpdump -nn(no DNS or service name lookups, no extra packets from your own capture). - Filter early:
host,port,tcp[tcpflags],udp port 53. - Read flags first:
[S]SYN,[S.]SYN/ACK,[.]ACK,[P.]data,[F.]FIN,[R]RST. - Compare timestamps between SYN and SYN/ACK for the handshake RTT.
- Only then dump bytes with
-XXor open the file in Wireshark.
| Filter | Shows |
|---|---|
tcpdump -nn -i en0 host 104.20.23.154 | All traffic to or from one host |
tcpdump -nn 'tcp[tcpflags] & tcp-syn != 0' | Every SYN and SYN/ACK |
tcpdump -nn udp port 53 | DNS |
tcpdump -nn -e arp | ARP with MAC addresses |
tcpdump -nn -s0 -w out.pcap | Save full packets to a file for Wireshark |
tcpdump -r out.pcap -XX | Read a file (no root needed) |
Choosing
| You want to... | Work at layer | Tool | Reason |
|---|---|---|---|
| Prove a host is alive | 3 | ping | ICMP needs no open port, but may be filtered |
| Prove a service accepts connections | 4 | nc -vz host port, curl -v | Completes a real handshake |
| Prove the application answers correctly | 7 | curl -v, HTTP client | Checks status, headers, body |
| See who is talking to whom | 4 | ss, lsof -i, netstat | Sockets and processes |
| See exact bytes and timing | 2-7 | tcpdump, Wireshark | Ground truth |
| Pick a load balancer for TCP/TLS passthrough | 4 | NLB, HAProxy tcp, IPVS | Cheap, protocol-agnostic |
| Route by URL, header, cookie | 7 | ALB, NGINX, Envoy | Needs HTTP parsing |
| Reach a private network | 3 | WireGuard, IPsec | Routes whole subnets |
| Reach one remote port | 4 | ssh -L | One socket forwarded, no admin |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
Everyday example: a Laravel or Go app on one VM serves https://shop.example/ and talks to PostgreSQL on 127.0.0.1:5432. Layers in play: browser to Nginx (L7 over TCP 443, TLS), Nginx to PHP-FPM or the Go process (TCP 127.0.0.1:9000 or a Unix socket, which skips IP entirely), app to database (TCP 5432 on loopback). Loopback has no MAC, no MTU of 1500, and no packet loss, so latency measurements here flatter reality. Production example: a database firewall rule that allows only 127.0.0.1 means a second app server cannot connect; the fix is a private address, not opening 5432 to the internet.
Modular monolith / multiple databases
The modules still share one process, but now two PostgreSQL hosts and a Redis sit on a private subnet (for example 10.0.2.0/24). Each connection is its own TCP stream with its own handshake; connection pools exist to pay that handshake (one RTT, plus TLS if enabled) once (Connection pooling). Security groups act at layers 3/4 (source subnet and port). Production example: after moving the database from the same host to another availability zone, each query gains about 0.5 to 1 ms of RTT; an N+1 query pattern that was invisible on loopback now costs N round trips, a layer 1 fact (propagation) showing up as an ORM problem.
Microservices
Everyday example: the orders service calls inventory over HTTP/2 (gRPC). On Kubernetes the call goes to a ClusterIP Service name; CoreDNS resolves it, kube-proxy DNATs the virtual IP to one pod, and with HTTP/2 keeping one long TCP connection the L4 balancing decision is made only once per connection, so all calls hit the same pod: the classic "gRPC does not load balance" bug, fixed with a client-side or L7 balancer. Production example: a service mesh sidecar (Envoy) terminates mTLS and balances per request at L7, at the cost of an extra two hops and extra copying. Details: Kubernetes networking, gRPC and Protobuf, HTTP evolution.
Distributed data, caches and edges
Across regions, propagation delay dominates: Frankfurt to Virginia is typically on the order of 90 ms RTT, no software fix helps, so you replicate data, cache at the edge (CDN) and choose the nearest endpoint by DNS (IP, DNS, GeoDNS). Replica lag, cross-region TLS handshakes (1 RTT each, so reuse connections) and path MTU across VPN tunnels (WireGuard commonly 1420) all trace back to layers 1 to 4. Production example: a primary in one region with a read replica in another; the replication stream is a single long-lived TCP connection, so its throughput is bounded by window size divided by RTT, not by link bandwidth.
Scaling path
| Scale | Network picture | Typical change |
|---|---|---|
| 1x: one server | Public IP, DNS A record, Nginx on 443 | Keep-alive, HTTP/2, TLS 1.3 |
| 10x: several app servers | L7 load balancer, private subnet, security groups | Health checks, connection draining, shared sessions |
| 100x: many services | L4 in front of L7, service discovery, mesh, mTLS | Connection pooling per upstream, timeouts per layer |
| Multi-region | GeoDNS or anycast, CDN, cross-region replication | Edge caching, async replication, regional failover |
| Very large | Anycast, ECMP, kernel bypass (DPDK, XDP) | Move work down the stack to save per-packet CPU |
Go
Raw TCP echo server and client
Layer 4 only: no HTTP, no framing. Because TCP is a byte stream, a single Write may arrive as several Read calls; real protocols add their own length prefix or delimiter.
// A raw TCP echo server: Layer 4 is all you need. No HTTP, no framing.
package main
import (
"fmt"
"io"
"log"
"net"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:9000") // bind() + listen()
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Printf("listening on %s", ln.Addr())
for {
conn, err := ln.Accept() // returns after the three-way handshake finished
if err != nil {
log.Print(err)
continue
}
go func(c net.Conn) {
defer c.Close()
fmt.Printf("peer %s -> local %s\n", c.RemoteAddr(), c.LocalAddr())
n, err := io.Copy(c, c) // read from the byte stream, write it back
log.Printf("echoed %d bytes, err=%v", n, err)
}(conn)
}
}// A raw TCP echo client. TCP is a byte stream: one Write may arrive as
// several Reads, so a real protocol needs its own message boundaries.
package main
import (
"fmt"
"io"
"log"
"net"
"time"
)
func main() {
conn, err := net.DialTimeout("tcp", "127.0.0.1:9000", 3*time.Second)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
fmt.Printf("local %s -> remote %s\n", conn.LocalAddr(), conn.RemoteAddr())
msg := []byte("hello, layer 4\n")
if _, err := conn.Write(msg); err != nil {
log.Fatal(err)
}
buf := make([]byte, len(msg))
if _, err := io.ReadFull(conn, buf); err != nil {
log.Fatal(err)
}
fmt.Printf("echo: %q\n", buf)
}Output on this machine (server and client in separate terminals):
$ go run ./echo/server $ go run ./echo/client
listening on 127.0.0.1:9000 local 127.0.0.1:56069 -> remote 127.0.0.1:9000
peer 127.0.0.1:56069 -> ... echo: "hello, layer 4\n"
echoed 15 bytes, err=<nil>
$ lsof -nP -iTCP:9000
server 95854 m.negahi 3u IPv4 ... TCP 127.0.0.1:9000 (LISTEN)HTTP by hand over the socket
// rawhttp speaks HTTP/1.1 by hand over a TCP socket: Layer 7 is just text.
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"time"
)
func main() {
host := "example.com"
if len(os.Args) > 1 {
host = os.Args[1]
}
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, "80"), 5*time.Second)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
// The request is plain bytes; CRLF line endings and the blank line matter.
fmt.Fprintf(conn, "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nUser-Agent: rawhttp/1\r\n\r\n", host)
r := bufio.NewReader(conn)
for i := 0; i < 8; i++ { // status line plus the first headers
line, err := r.ReadString('\n')
if err != nil {
break
}
fmt.Print(line)
}
}The same thing from a shell, with nc (captured here with a 3 second sleep so the server has time to answer):
$ (printf 'GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n'; sleep 3) | nc -w 10 example.com 80 | head -9
HTTP/1.1 200 OK
Date: Wed, 25 Nov 2026 17:13:52 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Age: 5
Server: cloudflare
Last-Modified: Tue, 24 Nov 2026 21:00:21 GMT
Allow: GET, HEADThe phases of a request, measured
net/http/httptrace hooks every phase of the URL journey. Output of the program below against http://example.com/ and https://example.com/ on this machine (through the TUN proxy, so DNS and the handshake are local and fast; the server think time includes the proxy's own upstream trip):
// urltrace prints the phases of "open a URL" using net/http/httptrace:
// DNS, TCP connect, TLS handshake, request write, first response byte.
package main
import (
"crypto/tls"
"fmt"
"io"
"log"
"net/http"
"net/http/httptrace"
"os"
"time"
)
func main() {
url := "http://example.com/"
if len(os.Args) > 1 {
url = os.Args[1]
}
var start, dnsStart, connStart, tlsStart, wrote time.Time
since := func() string { return fmt.Sprintf("%7.1f ms", float64(time.Since(start).Microseconds())/1000) }
trace := &httptrace.ClientTrace{
DNSStart: func(i httptrace.DNSStartInfo) { dnsStart = time.Now(); fmt.Println(since(), "DNS start", i.Host) },
DNSDone: func(i httptrace.DNSDoneInfo) {
fmt.Println(since(), "DNS done ", i.Addrs, "in", time.Since(dnsStart).Round(time.Microsecond))
},
ConnectStart: func(network, addr string) { connStart = time.Now(); fmt.Println(since(), "TCP connect to", addr) },
ConnectDone: func(network, addr string, err error) {
fmt.Println(since(), "TCP established, handshake took", time.Since(connStart).Round(time.Microsecond), "err =", err)
},
TLSHandshakeStart: func() { tlsStart = time.Now(); fmt.Println(since(), "TLS start") },
TLSHandshakeDone: func(s tls.ConnectionState, err error) {
fmt.Println(since(), "TLS done", tls.VersionName(s.Version), "in", time.Since(tlsStart).Round(time.Microsecond))
},
WroteRequest: func(httptrace.WroteRequestInfo) { wrote = time.Now(); fmt.Println(since(), "request written") },
GotFirstResponseByte: func() {
fmt.Println(since(), "first response byte, server think time", time.Since(wrote).Round(time.Millisecond))
},
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
start = time.Now()
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
n, _ := io.Copy(io.Discard, resp.Body)
fmt.Println(since(), resp.Proto, resp.Status, n, "body bytes")
}$ go run ./urltrace http://example.com/
0.6 ms DNS start example.com
5.2 ms DNS done [{198.18.1.39 }] in 4.639ms
5.3 ms TCP connect to 198.18.1.39:80
5.6 ms TCP established, handshake took 292µs err = <nil>
5.9 ms request written
646.4 ms first response byte, server think time 641ms
646.9 ms HTTP/1.1 200 OK 577 body bytes
$ go run ./urltrace https://example.com/
2.9 ms TCP connect to 198.18.1.39:443
3.1 ms TLS start
413.6 ms TLS done TLS 1.3 in 410.461ms
952.4 ms first response byte, server think time 538ms
952.5 ms HTTP/2.0 200 OK 577 body bytesHTTP/2 was negotiated by ALPN inside the TLS handshake (see TLS in practice and HTTP/2, HTTPS and TLS in Go). More on the client and server APIs: net/http.
Measuring the handshake RTT
connect() returns after SYN, SYN/ACK, ACK, so its duration is one round trip. A refused connection returns after the RST, which is also one RTT.
// handshakertt measures the TCP three-way handshake as seen by the client:
// connect() returns after SYN -> SYN/ACK -> ACK, so its duration is one RTT.
package main
import (
"errors"
"fmt"
"net"
"os"
"sort"
"syscall"
"time"
)
func main() {
addr := "example.com:80"
if len(os.Args) > 1 {
addr = os.Args[1]
}
// Optional second argument: local source IP. Binding to the Wi-Fi address
// makes the OS pick that interface, which bypasses a TUN-mode proxy.
dialer := net.Dialer{Timeout: 3 * time.Second}
if len(os.Args) > 2 {
dialer.LocalAddr = &net.TCPAddr{IP: net.ParseIP(os.Args[2])}
}
var d []time.Duration
for i := 0; i < 10; i++ {
t0 := time.Now()
c, err := dialer.Dial("tcp", addr)
d = append(d, time.Since(t0))
if err != nil {
// "connection refused" is a RST that came back: still exactly one RTT.
if !errors.Is(err, syscall.ECONNREFUSED) {
fmt.Println("dial:", err)
os.Exit(1)
}
} else {
_ = c.Close()
}
time.Sleep(100 * time.Millisecond)
}
sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
fmt.Printf("%s: min=%v median=%v max=%v\n", addr, d[0], d[len(d)/2], d[len(d)-1])
}$ go run ./handshakertt 127.0.0.1:63342
127.0.0.1:63342: min=133.666µs median=171.209µs max=448µs
$ go run ./handshakertt example.com:80 # through the TUN proxy: a local handshake
example.com:80: min=884.542µs median=956.334µs max=5.994292msBuilding frames: the capture used on this page
Pure encoding/binary: Ethernet, ARP, IPv4, UDP, TCP, DNS, the Internet checksum, and a pcap writer. The hex dumps in Headers decoded come from this program, decoded by tcpdump -r.
// frames builds five Ethernet frames byte by byte (ARP request, ARP reply,
// DNS query, TCP SYN, HTTP GET segment) and writes them to a pcap file, so
// `tcpdump -r frames.pcap -nn -e -XX` can decode them without root.
package main
import (
"encoding/binary"
"fmt"
"net"
"os"
"time"
)
var (
hostMAC = mustMAC("e6:22:8e:ba:6e:f0")
gwMAC = mustMAC("56:ba:6d:ec:d8:fe")
bcast = mustMAC("ff:ff:ff:ff:ff:ff")
hostIP = net.IPv4(10, 84, 50, 174).To4()
gwIP = net.IPv4(10, 84, 50, 254).To4()
dnsIP = net.IPv4(10, 84, 50, 254).To4()
webIP = net.IPv4(104, 20, 23, 154).To4()
)
func mustMAC(s string) net.HardwareAddr {
m, err := net.ParseMAC(s)
if err != nil {
panic(err)
}
return m
}
// ethernet prepends the 14-byte header: dst(6) src(6) ethertype(2).
func ethernet(dst, src net.HardwareAddr, etherType uint16, payload []byte) []byte {
b := make([]byte, 0, 14+len(payload))
b = append(b, dst...)
b = append(b, src...)
b = binary.BigEndian.AppendUint16(b, etherType)
return append(b, payload...)
}
// checksum is the Internet checksum (RFC 1071): ones-complement sum of 16-bit words.
func checksum(b []byte) uint16 {
var sum uint32
for i := 0; i+1 < len(b); i += 2 {
sum += uint32(binary.BigEndian.Uint16(b[i:]))
}
if len(b)%2 == 1 {
sum += uint32(b[len(b)-1]) << 8
}
for sum>>16 != 0 {
sum = sum&0xffff + sum>>16
}
return ^uint16(sum)
}
// ipv4 builds a 20-byte header (no options) followed by payload.
func ipv4(proto byte, id uint16, src, dst net.IP, payload []byte) []byte {
h := make([]byte, 20)
h[0] = 0x45 // version 4, IHL 5 (5 x 4 = 20 bytes)
binary.BigEndian.PutUint16(h[2:], uint16(20+len(payload)))
binary.BigEndian.PutUint16(h[4:], id)
binary.BigEndian.PutUint16(h[6:], 0x4000) // flags: DF, fragment offset 0
h[8] = 64 // TTL
h[9] = proto
copy(h[12:], src)
copy(h[16:], dst)
binary.BigEndian.PutUint16(h[10:], checksum(h))
return append(h, payload...)
}
// pseudoChecksum covers the pseudo-header (src, dst, zero, proto, length) plus the segment.
func pseudoChecksum(proto byte, src, dst net.IP, seg []byte) uint16 {
p := make([]byte, 0, 12+len(seg))
p = append(p, src...)
p = append(p, dst...)
p = append(p, 0, proto)
p = binary.BigEndian.AppendUint16(p, uint16(len(seg)))
p = append(p, seg...)
return checksum(p)
}
func arp(op uint16, sha net.HardwareAddr, spa net.IP, tha net.HardwareAddr, tpa net.IP) []byte {
b := make([]byte, 0, 28)
b = binary.BigEndian.AppendUint16(b, 1) // hardware type: Ethernet
b = binary.BigEndian.AppendUint16(b, 0x0800) // protocol type: IPv4
b = append(b, 6, 4) // hardware size, protocol size
b = binary.BigEndian.AppendUint16(b, op)
b = append(b, sha...)
b = append(b, spa...)
b = append(b, tha...)
return append(b, tpa...)
}
func dnsQuery(id uint16, name string) []byte {
b := binary.BigEndian.AppendUint16(nil, id)
b = binary.BigEndian.AppendUint16(b, 0x0100) // flags: RD (recursion desired)
b = binary.BigEndian.AppendUint16(b, 1) // QDCOUNT
b = append(b, 0, 0, 0, 0, 0, 0) // ANCOUNT, NSCOUNT, ARCOUNT
for _, label := range splitLabels(name) {
b = append(b, byte(len(label)))
b = append(b, label...)
}
b = append(b, 0) // root label
b = binary.BigEndian.AppendUint16(b, 1) // QTYPE A
return binary.BigEndian.AppendUint16(b, 1) // QCLASS IN
}
func splitLabels(name string) []string {
var out []string
start := 0
for i := 0; i <= len(name); i++ {
if i == len(name) || name[i] == '.' {
out = append(out, name[start:i])
start = i + 1
}
}
return out
}
func udp(sport, dport uint16, src, dst net.IP, payload []byte) []byte {
h := make([]byte, 8, 8+len(payload))
binary.BigEndian.PutUint16(h[0:], sport)
binary.BigEndian.PutUint16(h[2:], dport)
binary.BigEndian.PutUint16(h[4:], uint16(8+len(payload)))
seg := append(h, payload...)
binary.BigEndian.PutUint16(seg[6:], pseudoChecksum(17, src, dst, seg))
return seg
}
// tcp builds a 20-byte header (data offset 5) or, with opts, 20+len(opts) bytes.
func tcp(sport, dport uint16, seq, ack uint32, flags byte, opts, payload []byte) []byte {
hl := 20 + len(opts)
h := make([]byte, hl, hl+len(payload))
binary.BigEndian.PutUint16(h[0:], sport)
binary.BigEndian.PutUint16(h[2:], dport)
binary.BigEndian.PutUint32(h[4:], seq)
binary.BigEndian.PutUint32(h[8:], ack)
h[12] = byte(hl/4) << 4 // data offset in 32-bit words
h[13] = flags
binary.BigEndian.PutUint16(h[14:], 64240) // window
copy(h[20:], opts)
seg := append(h, payload...)
binary.BigEndian.PutUint16(seg[16:], pseudoChecksum(6, hostIP, webIP, seg))
return seg
}
func writePcap(path string, frames [][]byte) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
hdr := make([]byte, 0, 24)
hdr = binary.LittleEndian.AppendUint32(hdr, 0xa1b2c3d4) // magic, microsecond timestamps
hdr = binary.LittleEndian.AppendUint16(hdr, 2)
hdr = binary.LittleEndian.AppendUint16(hdr, 4)
hdr = binary.LittleEndian.AppendUint32(hdr, 0)
hdr = binary.LittleEndian.AppendUint32(hdr, 0)
hdr = binary.LittleEndian.AppendUint32(hdr, 65535) // snaplen
hdr = binary.LittleEndian.AppendUint32(hdr, 1) // LINKTYPE_ETHERNET
if _, err := f.Write(hdr); err != nil {
return err
}
t := time.Date(2026, 11, 25, 20, 40, 0, 0, time.UTC)
for i, fr := range frames {
ts := t.Add(time.Duration(i) * 3 * time.Millisecond)
rec := make([]byte, 0, 16+len(fr))
rec = binary.LittleEndian.AppendUint32(rec, uint32(ts.Unix()))
rec = binary.LittleEndian.AppendUint32(rec, uint32(ts.Nanosecond()/1000))
rec = binary.LittleEndian.AppendUint32(rec, uint32(len(fr)))
rec = binary.LittleEndian.AppendUint32(rec, uint32(len(fr)))
rec = append(rec, fr...)
if _, err := f.Write(rec); err != nil {
return err
}
}
return nil
}
func main() {
out := "frames.pcap"
if len(os.Args) > 1 {
out = os.Args[1]
}
zero := net.HardwareAddr{0, 0, 0, 0, 0, 0}
// SYN options: MSS 1460, SACK permitted, NOP, window scale 7 (12 bytes -> header 32).
synOpts := []byte{2, 4, 0x05, 0xb4, 4, 2, 1, 3, 3, 7, 1, 1}
req := []byte("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
frames := [][]byte{
ethernet(bcast, hostMAC, 0x0806, arp(1, hostMAC, hostIP, zero, gwIP)),
ethernet(hostMAC, gwMAC, 0x0806, arp(2, gwMAC, gwIP, hostMAC, hostIP)),
ethernet(gwMAC, hostMAC, 0x0800, ipv4(17, 0x1c46, hostIP, dnsIP, udp(53124, 53, hostIP, dnsIP, dnsQuery(0x3a7b, "example.com")))),
ethernet(gwMAC, hostMAC, 0x0800, ipv4(6, 0x1c47, hostIP, webIP, tcp(51234, 80, 0x1a2b3c4d, 0, 0x02, synOpts, nil))),
ethernet(gwMAC, hostMAC, 0x0800, ipv4(6, 0x1c48, hostIP, webIP, tcp(51234, 80, 0x1a2b3c4e, 0x9f8e7d6d, 0x18, nil, req))),
}
if err := writePcap(out, frames); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
for i, f := range frames {
fmt.Printf("frame %d: %d bytes\n", i+1, len(f))
}
}Reading packet headers with the standard library
// decode reads a classic pcap file and prints every header field by offset,
// using only encoding/binary. It is the "what tcpdump does" in 90 lines.
package main
import (
"encoding/binary"
"fmt"
"net"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: decode file.pcap")
os.Exit(2)
}
data, err := os.ReadFile(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
pos := 24 // skip the 24-byte pcap global header
for n := 1; pos+16 <= len(data); n++ {
caplen := int(binary.LittleEndian.Uint32(data[pos+8:]))
frame := data[pos+16 : pos+16+caplen]
pos += 16 + caplen
fmt.Printf("== frame %d: %d bytes\n", n, len(frame))
ethernet(frame)
}
}
func ethernet(f []byte) {
etype := binary.BigEndian.Uint16(f[12:])
fmt.Printf(" [0:6] eth dst %s\n [6:12] eth src %s\n [12:14] ethertype 0x%04x\n",
net.HardwareAddr(f[0:6]), net.HardwareAddr(f[6:12]), etype)
switch etype {
case 0x0806:
arp(f[14:])
case 0x0800:
ipv4(f[14:])
}
}
func arp(b []byte) {
fmt.Printf(" [14:16] hw type %d (Ethernet)\n [16:18] proto type 0x%04x\n [20:22] opcode %d\n",
binary.BigEndian.Uint16(b[0:]), binary.BigEndian.Uint16(b[2:]), binary.BigEndian.Uint16(b[6:]))
fmt.Printf(" [22:28] sender MAC %s\n [28:32] sender IP %s\n [32:38] target MAC %s\n [38:42] target IP %s\n",
net.HardwareAddr(b[8:14]), net.IP(b[14:18]), net.HardwareAddr(b[18:24]), net.IP(b[24:28]))
}
func ipv4(b []byte) {
ihl := int(b[0]&0x0f) * 4
total := int(binary.BigEndian.Uint16(b[2:]))
flags := binary.BigEndian.Uint16(b[6:]) >> 13
fmt.Printf(" [14] version/IHL %d / %d (= %d bytes)\n", b[0]>>4, b[0]&0x0f, ihl)
fmt.Printf(" [16:18] total length %d\n [18:20] identification 0x%04x\n [20:22] flags/frag DF=%v offset=%d\n",
total, binary.BigEndian.Uint16(b[4:]), flags&0x2 != 0, binary.BigEndian.Uint16(b[6:])&0x1fff)
fmt.Printf(" [22] TTL %d\n [23] protocol %d\n [24:26] header checksum 0x%04x\n [26:30] src IP %s\n [30:34] dst IP %s\n",
b[8], b[9], binary.BigEndian.Uint16(b[10:]), net.IP(b[12:16]), net.IP(b[16:20]))
payload := b[ihl:total]
switch b[9] {
case 6:
tcp(payload)
case 17:
udp(payload)
}
}
func tcp(b []byte) {
off := int(b[12]>>4) * 4
fmt.Printf(" [34:36] src port %d\n [36:38] dst port %d\n [38:42] seq %d\n [42:46] ack %d\n",
binary.BigEndian.Uint16(b[0:]), binary.BigEndian.Uint16(b[2:]), binary.BigEndian.Uint32(b[4:]), binary.BigEndian.Uint32(b[8:]))
fmt.Printf(" [46] data offset %d (= %d bytes header, %d bytes options)\n [47] flags 0x%02x\n [48:50] window %d\n [50:52] checksum 0x%04x\n payload %d bytes\n",
b[12]>>4, off, off-20, b[13], binary.BigEndian.Uint16(b[14:]), binary.BigEndian.Uint16(b[16:]), len(b)-off)
}
func udp(b []byte) {
fmt.Printf(" [34:36] src port %d\n [36:38] dst port %d\n [38:40] length %d\n [40:42] checksum 0x%04x\n [42:44] DNS id 0x%04x\n [44:46] DNS flags 0x%04x\n [46:48] QDCOUNT %d\n",
binary.BigEndian.Uint16(b[0:]), binary.BigEndian.Uint16(b[2:]), binary.BigEndian.Uint16(b[4:]), binary.BigEndian.Uint16(b[6:]),
binary.BigEndian.Uint16(b[8:]), binary.BigEndian.Uint16(b[10:]), binary.BigEndian.Uint16(b[12:]))
}$ go run ./decode frames.pcap | sed -n '/frame 4/,/frame 5/p'
== frame 4: 66 bytes
[0:6] eth dst 56:ba:6d:ec:d8:fe
[12:14] ethertype 0x0800
[14] version/IHL 4 / 5 (= 20 bytes)
[16:18] total length 52
[22] TTL 64
[23] protocol 6
[26:30] src IP 10.84.50.174
[30:34] dst IP 104.20.23.154
[34:36] src port 51234
[36:38] dst port 80
[38:42] seq 439041101
[46] data offset 8 (= 32 bytes header, 12 bytes options)
[47] flags 0x02
payload 0 bytesReading packet headers with gopacket
github.com/google/gopacket decodes layers for you. The offline reader pcapgo is pure Go (no libpcap, no root). Live capture with pcap.OpenLive needs libpcap headers (cgo) and root, so it is only compiled-and-described here, not run.
// gopacketdump decodes a pcap file offline with gopacket. pcapgo is pure Go,
// so no libpcap or root is needed; live capture (pcap.OpenLive) would need both.
package main
import (
"fmt"
"os"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcapgo"
)
func main() {
f, err := os.Open(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer f.Close()
r, err := pcapgo.NewReader(f)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
src := gopacket.NewPacketSource(r, r.LinkType())
for p := range src.Packets() {
var layerNames []string
for _, l := range p.Layers() {
layerNames = append(layerNames, l.LayerType().String())
}
fmt.Println(layerNames)
if ip, ok := p.Layer(layers.LayerTypeIPv4).(*layers.IPv4); ok {
fmt.Printf(" IPv4 %s -> %s ttl=%d proto=%s ihl=%d\n", ip.SrcIP, ip.DstIP, ip.TTL, ip.Protocol, ip.IHL)
}
if t, ok := p.Layer(layers.LayerTypeTCP).(*layers.TCP); ok {
fmt.Printf(" TCP %d -> %d seq=%d SYN=%v ACK=%v PSH=%v payload=%dB\n", t.SrcPort, t.DstPort, t.Seq, t.SYN, t.ACK, t.PSH, len(t.Payload))
}
}
}$ go run ./gopacketdump frames.pcap
[Ethernet ARP]
[Ethernet ARP]
[Ethernet IPv4 UDP DNS]
IPv4 10.84.50.174 -> 10.84.50.254 ttl=64 proto=UDP ihl=5
[Ethernet IPv4 TCP]
IPv4 10.84.50.174 -> 104.20.23.154 ttl=64 proto=TCP ihl=5
TCP 51234 -> 80 seq=439041101 SYN=true ACK=false PSH=false payload=0B
[Ethernet IPv4 TCP Payload]
IPv4 10.84.50.174 -> 104.20.23.154 ttl=64 proto=TCP ihl=5
TCP 51234 -> 80 seq=439041102 SYN=false ACK=true PSH=true payload=56BRaw sockets on Linux
A raw AF_PACKET socket delivers entire Ethernet frames to your program. It needs root or CAP_NET_RAW, exists only on Linux, and is the mechanism under tcpdump there. The file carries a //go:build linux tag, so it was checked with GOOS=linux go vet and not run on this Mac. On macOS the equivalent is BPF (/dev/bpf*) accessed through libpcap. For anything beyond learning, use gopacket or libpcap rather than hand-written syscall code.
//go:build linux
// rawsock reads whole Ethernet frames from a Linux AF_PACKET socket. It needs
// root (or CAP_NET_RAW) and does not exist on macOS, where you use BPF
// (/dev/bpf*) through libpcap instead.
package main
import (
"fmt"
"log"
"syscall"
)
// htons converts a 16-bit value to network byte order on little-endian hosts.
func htons(v uint16) uint16 { return v<<8 | v>>8 }
func main() {
const ethPAll = 0x0003 // every protocol
fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, int(htons(ethPAll)))
if err != nil {
log.Fatalf("socket: %v (run as root)", err)
}
defer syscall.Close(fd)
buf := make([]byte, 65536)
for i := 0; i < 5; i++ {
n, _, err := syscall.Recvfrom(fd, buf, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("frame %d: %d bytes, ethertype 0x%02x%02x\n", i+1, n, buf[12], buf[13])
}
}Laravel and PHP
PHP is not installed on the machine used to write this page, so the PHP files were reviewed against the PHP manual and the Laravel 13 HTTP client documentation, not executed.
HTTP by hand with fsockopen
<?php
declare(strict_types=1);
// HTTP/1.1 by hand over a plain TCP socket (Layer 7 on top of Layer 4).
// Run: php RawHttp.php example.com
$host = $argv[1] ?? 'example.com';
$fp = fsockopen($host, 80, $errno, $errstr, 5.0); // resolves DNS, then connect()
if ($fp === false) {
fwrite(STDERR, "connect failed: [$errno] $errstr\n");
exit(1);
}
stream_set_timeout($fp, 10);
// The request is just bytes. CRLF line endings and the blank line matter.
fwrite($fp, "GET / HTTP/1.1\r\nHost: {$host}\r\nConnection: close\r\nUser-Agent: raw-php/1\r\n\r\n");
for ($i = 0; $i < 8 && ! feof($fp); $i++) { // status line plus the first headers
echo fgets($fp);
}
fclose($fp);stream_socket_client: the same socket with more control
fsockopen is a shortcut for stream_socket_client with a tcp:// address. The stream version accepts connect flags and a stream context, and stream_socket_get_name returns the local and remote addresses, the ephemeral port included.
<?php
declare(strict_types=1);
// stream_socket_client gives the same socket with more control:
// an explicit scheme, connect flags, a stream context and the local/remote address.
$context = stream_context_create([
'socket' => [
'bindto' => '0:0', // let the kernel choose the source IP and ephemeral port
'tcp_nodelay' => true, // disable Nagle: send small writes immediately
],
]);
$start = microtime(true);
$fp = stream_socket_client(
'tcp://example.com:80',
$errno,
$errstr,
5.0,
STREAM_CLIENT_CONNECT,
$context,
);
if ($fp === false) {
fwrite(STDERR, "connect failed: [$errno] $errstr\n");
exit(1);
}
$connectMs = (microtime(true) - $start) * 1000; // DNS + TCP handshake, together
printf("local %s\n", stream_socket_get_name($fp, false)); // 10.0.0.5:51234
printf("remote %s\n", stream_socket_get_name($fp, true)); // 93.184.x.x:80
printf("connect took %.1f ms (DNS + handshake)\n", $connectMs);
fwrite($fp, "HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");
echo stream_get_line($fp, 4096, "\r\n"), "\n"; // HTTP/1.1 200 OK
fclose($fp);A raw echo server
<?php
declare(strict_types=1);
// A raw TCP echo server with stream_socket_server: Layer 4 without HTTP.
// One client at a time; real servers use stream_select or Swoole/Octane.
$server = stream_socket_server('tcp://127.0.0.1:9000', $errno, $errstr);
if ($server === false) {
fwrite(STDERR, "bind failed: [$errno] $errstr\n");
exit(1);
}
echo "listening on ", stream_socket_get_name($server, false), "\n";
while (($conn = stream_socket_accept($server, -1, $peer)) !== false) {
echo "peer {$peer}\n";
while (! feof($conn) && ($data = fread($conn, 8192)) !== '' && $data !== false) {
fwrite($conn, $data); // echo the bytes back
}
fclose($conn);
}The Laravel HTTP client seen through tcpdump
Http::get() is Guzzle over cURL. Http::connectTimeout(3) limits the TCP handshake (default 10 seconds), timeout() limits the whole request, and withOptions(['on_stats' => ...]) exposes cURL's own phase timers: the same numbers curl -w prints.
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use GuzzleHttp\TransferStats;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
// Laravel 13: the HTTP client wraps Guzzle, which wraps cURL. cURL's own timers
// (DNS, connect, TLS, first byte) are the same numbers `curl -w` prints.
class NetTimings extends Command
{
protected $signature = 'net:timings {url=http://example.com/}';
protected $description = 'Show DNS / TCP / TLS / first-byte timings of one request';
public function handle(): int
{
$response = Http::connectTimeout(3)
->timeout(10)
->withOptions([
'on_stats' => function (TransferStats $stats): void {
$h = $stats->getHandlerStats(); // raw curl_getinfo() array
$this->table(['phase', 'seconds (cumulative)'], [
['primary_ip', $h['primary_ip'] ?? '?'],
['namelookup (DNS)', $h['namelookup_time'] ?? '?'],
['connect (TCP handshake done)', $h['connect_time'] ?? '?'],
['appconnect (TLS done)', $h['appconnect_time'] ?? '?'],
['starttransfer (first byte)', $h['starttransfer_time'] ?? '?'],
['total', $h['total_time'] ?? '?'],
]);
},
])
->get($this->argument('url'));
$this->info($response->status().' '.strlen($response->body()).' bytes');
return self::SUCCESS;
}
}What tcpdump -nn -A 'tcp port 80' shows while this runs is exactly the bytes from Frame 5: GET / HTTP/1.1, Host: example.com, plus the client's own User-Agent and Accept lines. For curl 8.7.1 on this machine, curl -v shows:
> GET / HTTP/1.1
> Host: example.com
> User-Agent: curl/8.7.1
> Accept: */*Laravel adds User-Agent: GuzzleHttp/7 and Accept-Encoding according to its options. Over HTTPS the same capture shows only the TLS handshake and encrypted records; tcpdump cannot see the request, which is why curl -v and framework logging exist.
Lab
Live capture needs root. Everything else runs unprivileged.
- Show your interfaces and route. macOS:
ifconfig en0 | head -5,netstat -rn -f inet | head,route -n get example.com. Linux:ip -br a,ip route get 1.1.1.1. Find your MAC, IPv4, gateway and MTU. - Capture one
curland annotate every packet.Expected shape (documentation-range addresses; yours differ):# terminal 1 (macOS: replace eth0 with en0; Linux: -i eth0) sudo tcpdump -nn -i en0 -w /tmp/curl.pcap 'host 104.20.23.154 or port 53' # terminal 2 curl -s -o /dev/null --resolve example.com:80:104.20.23.154 http://example.com/ # stop tcpdump with Ctrl-C, then read it with no root: tcpdump -nn -r /tmp/curl.pcap -ttAnnotate: 1-3 handshake (1 RTT = 158 ms here), 4 request, 5 ACK from the kernel (not the app), 6 response (the gap 4 to 6 is server think time plus RTT), the final1 0.000 10.0.0.5.51234 > 104.20.23.154.80: Flags [S], seq 1000, options [mss 1460,sackOK,TS val ..,nop,wscale 7] 2 0.158 104.20.23.154.80 > 10.0.0.5.51234: Flags [S.], seq 7000, ack 1001, options [mss 1460,...] 3 0.158 10.0.0.5.51234 > 104.20.23.154.80: Flags [.], ack 7001 4 0.158 10.0.0.5.51234 > 104.20.23.154.80: Flags [P.], seq 1001:1076, ack 7001 <- GET / (75 bytes with curl's headers) 5 0.176 104.20.23.154.80 > 10.0.0.5.51234: Flags [.], ack 1076 6 0.331 104.20.23.154.80 > 10.0.0.5.51234: Flags [P.], seq 7001:8461, ack 1076 <- first response segment: 1460 bytes = one MSS 7 ... more data segments, then [F.] / [.] / [F.] / [.]Fpackets close the connection. With-eadd MACs: the destination MAC is always your gateway's, never the server's. - Measure the handshake RTT.
curl -s -o /dev/null -w 'tcp=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' --interface en0 --resolve example.com:80:104.20.23.154 http://example.com/three times. On this Mac (through Wi-Fi, bypassing the TUN proxy):tcp=2.79 s,0.117 s,0.391 s, ttfb3.16 s,0.278 s,1.011 s. Subtract:ttfb - tcpis request, server time and response;tcpalone is one RTT. Compare with the Go program and withping. - Show the MTU with
ping -D -s.-Dsets DF (macOS; Linux uses-M do),-ssets the ICMP payload size. Packet size = payload + 8 ICMP + 20 IP. For MTU 1500 the largest payload is 1500 - 28 = 1472.1472 passes (the reply shows 1480 = 1472 + 8 ICMP; the IP header is not counted), 1473 does not: 1473 + 8 + 20 = 1501 > 1500. On this Mac the full output of the second command is$ ping -c 1 -D -s 1472 -n 10.84.50.254 # real output, default gateway PING 10.84.50.254 (10.84.50.254): 1472 data bytes 1480 bytes from 10.84.50.254: icmp_seq=0 ttl=64 time=8.007 ms $ ping -c 1 -D -s 1473 -n 10.84.50.254 1 packets transmitted, 0 packets received, 100.0% packet lossping: sendto: Message too longfollowed byRequest timeout for icmp_seq 0: the local kernel refuses to send a DF packet that does not fit the interface MTU. Linux printsping: local error: message too long, mtu=1500. When the too-small MTU is further along the path instead, the router answers with ICMP type 3 code 4 (Frag needed and DF set), and if that ICMP is filtered you get silence. - Decode a frame by hand. Build the pcap and decode it:
go run ./frames frames.pcap && tcpdump -r frames.pcap -nn -e -XX && go run ./decode frames.pcap. Compare the table of Frame 4 with the hex. - Raw HTTP by hand.
printf 'GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n' | nc example.com 80. RemoveHost:and watch the server answer 400 (HTTP/1.1 requires the header). - Find which layer fails.
ping -c1 10.84.50.254(L3 to gateway) thendig example.com(L7 DNS) thennc -vz example.com 80(L4) thencurl -v http://example.com/(L7). The first command that fails names the layer.
Common misconceptions
| Belief | Reality |
|---|---|
| The internet uses the OSI model | It uses TCP/IP; OSI supplies the vocabulary |
| Every packet passes through seven layers | Application, presentation and session collapse into one program; only 4 layers exist in the stack |
| TLS is layer 6 (or 5, or 4) | It runs above TCP and below HTTP; the label is arbitrary |
| A router changes the IP addresses | Only NAT does; ordinary routers change the MAC and the TTL |
| The destination MAC is the server's | It is the next hop's; the server's MAC is never seen by a remote client |
ping works, so the service works | ICMP only proves L3; the port and the app are separate checks |
| TCP delivers messages | It delivers a byte stream; boundaries are your job |
| Bigger bandwidth means lower latency | Propagation delay is fixed by distance |
| 127.0.0.1 and my LAN IP are the same | Loopback is unreachable from other hosts |
| A Kubernetes Service is a process | It is a virtual IP implemented by NAT rules |
| Packet captures on the sender show true checksums | Offload can leave them blank until the NIC fills them in |
| A VPN works at the HTTP level | It carries IP packets, so every protocol goes through it |
Cheat sheet
| Topic | What to remember |
|---|---|
| Layer jobs | L2 same link (MAC), L3 between networks (IP), L4 which program (port), L7 the message |
| Header sizes | Ethernet 14, IPv4 20, TCP 20, UDP 8; add options by Data Offset / IHL |
| Frame budget | 1500 MTU = 20 IP + 20 TCP + 1460 MSS payload; frame 1514 without FCS |
| EtherTypes | 0x0800 IPv4, 0x0806 ARP, 0x86DD IPv6 |
| IP protocol numbers | 1 ICMP, 6 TCP, 17 UDP |
| URL journey | parse, DNS, TCP, TLS, HTTP, response, render; costs 1 RTT per round trip stage |
| Who rewrites what | Router: MAC and TTL; NAT: IP and port; proxy: the whole connection |
| End-to-end | Do correctness at the endpoints; middleboxes are exceptions that cause bugs |
| Latency | propagation + serialization + queuing + processing; only distance fixes the first |
| refused vs timeout | refused = a RST came back (L4 alive); timeout = silence (drop or no route) |
| Linux tools | ip link/addr/route/neigh, ss -tulpn, tcpdump -nn, dig |
| macOS tools | ifconfig, netstat -rn, arp -an, lsof -i, scutil --dns, tcpdump -i en0 |
| Capture without root | tcpdump -r file.pcap, Wireshark, gopacket with pcapgo |
| MTU test | ping -D -s 1472 (macOS), ping -M do -s 1472 (Linux) |
| Loopback | no MAC, no ARP, huge MTU, never leaves the host |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Which two OSI layers have no separate software in a real TCP/IP stack, and where does their work happen? Good to know
Answer
Answer: Layers 5 (session) and 6 (presentation). RFC 1122 folds presentation into the application layer; encoding, TLS, compression and session handling are done by libraries and the application itself.
2 — A TCP segment carries 56 bytes of HTTP. How many bytes is the Ethernet frame (without FCS), and why? Important
Answer
Answer: 110: 14 Ethernet + 20 IPv4 + 20 TCP + 56 payload, assuming no IP or TCP options.
3 — Why is the MSS 1460 on Ethernet? Must-know
Answer
Answer: MTU 1500 minus 20 bytes IPv4 header minus 20 bytes TCP header. The MSS is announced as a TCP option in the SYN.
4 — In the SYN dump, the Data Offset nibble is 8. What does that tell you? Good to know
Answer
Answer: The TCP header is 8 x 4 = 32 bytes, i.e. 20 bytes base plus 12 bytes of options (MSS, SACK permitted, window scale, padding).
5 — Which MAC is the destination in the frame that carries your request to a server in another country? Must-know
Answer
Answer: The MAC of your default gateway (the next hop). The destination IP stays the server's; only ARP for the gateway was needed.
6 — What does a router do to a packet it forwards? Must-know
Answer
Answer: It strips and rewrites the L2 header for the next link, decrements the TTL and recomputes the IPv4 header checksum. It does not change IP addresses or ports (NAT does).
7 — ping -D -s 1472 succeeds and -s 1473 fails on an Ethernet link. Why? Important
Answer
Answer: 1472 + 8 (ICMP) + 20 (IP) = 1500 equals the MTU; 1473 makes 1501, which does not fit with DF set.
8 — Name the three delays that make up packet latency and which one bandwidth reduces. Important
Answer
Answer: Propagation (distance), serialization (size over rate) and queuing (waiting in buffers). More bandwidth reduces serialization only.
9 — Why does a gRPC client often hit only one pod behind a Kubernetes Service? Must-know
Answer
Answer: The Service balances per TCP connection (L4 NAT). HTTP/2 multiplexes all calls over one long connection, so one backend gets all of them; use client-side balancing or an L7 proxy.
10 — Explain "connection refused" versus "timed out" in layer terms. Must-know
Answer
Answer: Refused: a TCP RST came back, so IP routing works and the host answered but nothing listens (or a REJECT rule fired). Timed out: nothing came back, so a packet was dropped, a firewall silently denied it, or the route/host is dead.
11 — Why can a TUN-mode proxy make a 150 ms path look like 0.3 ms? Good to know
Answer
Answer: It terminates the TCP handshake locally on a tunnel interface and relays separately, so the client measures its own machine, not the real server. It is an end-to-end violation.
Glossary
| Term | Meaning |
|---|---|
| OSI model | Seven-layer reference model from ISO; mostly a vocabulary |
| TCP/IP model | Four-layer Internet model: link, internet, transport, application (RFC 1122) |
| Layer | A level of the stack offering a service to the layer above |
| Encapsulation | Wrapping a PDU as the payload of the next lower layer |
| Decapsulation | Removing a layer's header on the way up |
| PDU | Protocol data unit: frame, packet, segment, datagram, message |
| Frame | Layer 2 PDU, e.g. an Ethernet frame |
| Packet | Layer 3 PDU, e.g. an IP packet |
| Segment | TCP PDU |
| Datagram | UDP PDU (and the IPv4 name of a packet in RFC 791) |
| MAC address | 48-bit link-layer address, meaningful on one link |
| EtherType | 2-byte field naming the payload protocol (0x0800 IPv4, 0x0806 ARP) |
| FCS | Frame check sequence: Ethernet CRC-32 trailer |
| IPv4 header / IHL | 20-byte network header; IHL gives its length in 32-bit words |
| TTL | Hop limit decremented by each router; 0 drops the packet |
| MTU | Largest IP packet a link carries (1500 on Ethernet) |
| MSS | Largest TCP payload per segment (1460 on Ethernet/IPv4) |
| Path MTU Discovery | Learning the smallest MTU on a path through ICMP "fragmentation needed" (RFC 1191) |
| DF bit | Don't Fragment flag in the IPv4 header |
| ARP | Address Resolution Protocol: IPv4 address to MAC (RFC 826) |
| NDP | Neighbor Discovery Protocol: ARP's job in IPv6 |
| Three-way handshake | SYN, SYN/ACK, ACK opening a TCP connection |
| ISN | Initial sequence number chosen in the SYN |
| Window scale | TCP option multiplying the advertised window |
| SACK | Selective acknowledgment option |
| Ephemeral port | Short-lived client-side port chosen by the kernel |
| Socket | Kernel object identified by protocol, local address and port, remote address and port |
| Switch | Layer 2 device forwarding by MAC |
| Router | Layer 3 device forwarding by IP |
| NAT / PAT | Rewriting IP addresses / addresses and ports |
| Middlebox | Intermediary doing more than IP forwarding (RFC 3234) |
| End-to-end principle | Place correctness functions at the endpoints (Saltzer et al.) |
| Fate-sharing | Keep connection state only in endpoints (RFC 1958) |
| Loopback | Virtual interface for local traffic, 127.0.0.1 and ::1 |
| veth | Linux virtual Ethernet pair connecting a container to a bridge |
| TUN interface | Virtual L3 interface used by VPNs and proxies |
| pcap | File format for captured packets |
| BPF | Packet filter facility used by tcpdump on BSD/macOS |
| Propagation delay | Time for a signal to travel the distance |
| Serialization delay | Time to put all bits of a frame on the wire |
| Queuing delay | Time spent waiting in a buffer |
| RTT | Round-trip time |
| Offload (TSO, GSO, GRO) | NIC or kernel features that batch or split packets |
| Anycast | Same IP announced from many places; routing picks the nearest |
References
Fetched, read and saved under the session scratchpad sources/network-models-osi-tcpip/; each returned HTTP 200.
- Saltzer, Reed, Clark, "End-to-End Arguments in System Design" (1984), the quote at the top: https://web.mit.edu/Saltzer/www/publications/endtoend/endtoend.pdf
- RFC 791 Internet Protocol: https://www.rfc-editor.org/rfc/rfc791
- RFC 768 UDP: https://www.rfc-editor.org/rfc/rfc768
- RFC 9293 TCP: https://www.rfc-editor.org/rfc/rfc9293
- RFC 826 ARP: https://www.rfc-editor.org/rfc/rfc826
- RFC 894 IP over Ethernet: https://www.rfc-editor.org/rfc/rfc894
- RFC 1035 DNS implementation and specification: https://www.rfc-editor.org/rfc/rfc1035
- RFC 1122 Requirements for Internet Hosts, Communication Layers: https://www.rfc-editor.org/rfc/rfc1122
- RFC 1191 Path MTU Discovery: https://www.rfc-editor.org/rfc/rfc1191
- RFC 1958 Architectural Principles of the Internet: https://www.rfc-editor.org/rfc/rfc1958
- RFC 3234 Middleboxes: Taxonomy and Issues: https://www.rfc-editor.org/rfc/rfc3234
- RFC 3439 Some Internet Architectural Guidelines and Philosophy: https://www.rfc-editor.org/rfc/rfc3439
- RFC 3986 URI generic syntax: https://www.rfc-editor.org/rfc/rfc3986
- RFC 6691 TCP Options and MSS: https://www.rfc-editor.org/rfc/rfc6691
- tcpdump manual: https://www.tcpdump.org/manpages/tcpdump.1.html
- ip(8): https://man7.org/linux/man-pages/man8/ip.8.html ; ss(8): https://man7.org/linux/man-pages/man8/ss.8.html
- PostgreSQL system information functions: https://www.postgresql.org/docs/current/functions-info.html
- Docker bridge network driver: https://docs.docker.com/engine/network/drivers/bridge/
- Kubernetes Services, virtual IPs and service proxies: https://kubernetes.io/docs/concepts/services-networking/service/
- WireGuard: https://www.wireguard.com/
- PHP manual: https://www.php.net/manual/en/function.fsockopen.php , https://www.php.net/manual/en/function.stream-socket-client.php
- Laravel 13 HTTP client: https://laravel.com/docs/13.x/http-client