Skip to content

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 forGo to
The ten networking chapters and what each ownsThe networking group map
A table you can memorise in a minuteEverything in one minute
Why layers exist, and the three misunderstandingsWhy layers exist
Where OSI, TCP/IP, RFC 1122 and the "5 layers" come fromWhere the models come from
The seven OSI layers, which two are fictionOSI, one layer at a time
The four/five-layer model and the mapping tableTCP/IP and the mapping
Wrapping, unwrapping, MTU, MSS, byte offsetsEncapsulation and decapsulation
Hex dumps of ARP, DNS, TCP SYN, an HTTP segmentHeaders decoded from a capture
URL parse, DNS, TCP, TLS, HTTP, hops, NAT, renderWhat happens when you open a URL
MAC, IP, port, URL; frame, packet, segmentAddressing and PDU names
Switch, router, firewall, proxy, load balancerDevices per layer
Sockets, Docker bridge, Kubernetes Service, VPNWhere developers meet each layer
End-to-end principle, middleboxesThe end-to-end principle
Propagation, serialization, queuingLatency anatomy
ip, ifconfig, ss, tcpdump, loopbackInterfaces and tools
Go and PHP codeGo, Laravel and PHP
Reproduce it on your laptopLab

The networking group map ​

The ten networking chapters, by layerL7 DNS Resolution for Developers | (TLS in Practice, FN 01)L4 Ports, Sockets & Connections | Firewalls (iptables, nftables, Security Groups)L3 IP Addressing & Subnets | NAT, DHCP & Port Forwarding | VPNs & TunnelsL2 Docker Networking (bridge, veth) | Kubernetes Networking (CNI, Services)All layers Network Models (this chapter, entry) | Network Troubleshooting Playbook (exit)Reading order: models, IP, NAT/DHCP, DNS, ports/sockets, firewalls, Docker, Kubernetes, VPN, troubleshooting.
#ChapterMostly lives atWhat it owns
1Network Models (this page)all layersThe map, encapsulation, the URL journey, tool basics
2IP addressing, subnets, CIDRL3 (and ARP at L2)IPv4/IPv6, private ranges, subnet math, gateways, routing tables, ARP/NDP
3NAT, DHCP, port forwardingL3/L4PAT, DHCP lease flow, CGNAT, hairpin NAT
4DNS resolutionL7Resolvers, records, TTL, /etc/hosts, resolv.conf, split DNS
5Ports, sockets, connectionsL4Ephemeral ports, TIME_WAIT, keepalive, backlog, conntrack
6FirewallsL3/L4iptables, nftables, security groups, NACLs, egress control
7Docker networkingL2/L3bridge, host, overlay, macvlan, published ports, MTU
8Kubernetes networkingL3/L4/L7CNI, Services, kube-proxy, CoreDNS, Ingress, NetworkPolicy
9VPNs and tunnelsL3 over L4SSH forwarding, bastions, WireGuard, zero-trust access
10Troubleshooting playbookall layersRefused 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 nameUnit (PDU)AddressTypical protocolsDevice that caresWhere you meet it
7 ApplicationApplicationmessage / dataURL, host nameHTTP, DNS, SMTP, gRPCL7 proxy, WAFfetch, curl, HTTP clients
6 PresentationApplicationdatamedia type, charsetTLS records, JSON, UTF-8(none, done inside the app)Content-Type, encodings
5 SessionApplicationdatasession id, cookieRPC sessions, TLS resumption(none)Cookies, tokens
4 TransportTransportsegment (TCP), datagram (UDP)portTCP, UDP, QUICL4 load balancer, firewall, NATSockets, ss, nc
3 NetworkInternetpacketIP addressIPv4, IPv6, ICMProuter, L3 firewallip route, ping, VPN
2 Data linkLinkframeMAC addressEthernet, Wi-Fi, ARPswitch, bridgeip link, Docker bridge
1 PhysicalLinkbits(none)copper, fibre, radiohub, repeater, cableLink light, ethtool

The wrapping, in bytes (one GET, 56 bytes of text):

StepHeader addedSizeRunning total
HTTP text(none)5656
+ TCPsource port, destination port, seq, ack, flags20 (up to 60 with options)76
+ IPv4source IP, destination IP, TTL, protocol20 (up to 60 with options)96
+ Ethernetdestination MAC, source MAC, EtherType14110
(+ FCS)CRC-32 trailer, stripped by the NIC before tcpdump sees it4114 on the wire

The numbers to remember.

NumberMeaning
1500Ethernet MTU: largest IP packet one frame carries
1460TCP MSS on Ethernet: 1500 - 20 (IP) - 20 (TCP)
14 / 20 / 20Ethernet / IPv4 / TCP base header sizes
8UDP header size
64Default IP TTL on Linux and macOS
0x0800 / 0x0806 / 0x86DDEtherType: IPv4 / ARP / IPv6
6 / 17 / 1IP protocol numbers: TCP / UDP / ICMP
80 / 443 / 53HTTP / 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 layersWith layers
One giant protocol; every change touches everythingEach layer talks only to the layer above and below
Applications must know about cables and radiosApplications open a socket and write bytes
One vendor owns the whole stackMany vendors per layer interoperate (a switch from one, a router from another)
Debugging means guessingDebugging means finding the layer, then its header

Three misunderstandings, up front.

BeliefReality
"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.

SourceWhat it saysUsed 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 wordsByte offsets
RFC 9293 (2022)TCP header, MSS option, default send MSS 536 for IPv4 when no option arrivesMSS and the SYN options
RFC 826ARP packet layout (hardware type, protocol type, opcode)ARP dump
RFC 1035DNS header and question format, UDP messages 512 octets or lessDNS dump
RFC 3986URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]URL parsing
RFC 3234A 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 optimiseWhy real stacks cheat
Saltzer et al. 1984The end-to-end argumentEnd-to-end section
Docker docs, Kubernetes docs, WireGuard siteBridge = 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-know

In 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.

OSI (7)5-layer teaching modelTCP/IP (RFC 1122, 4)Examples / PDU7 ApplicationHTTP, DNS, SMTP: the real thing6 PresentationTLS, JSON, UTF-8: done by the app5 Sessioncookies, RPC sessions: done by the app4 TransportTCP, UDP, QUIC: ports3 NetworkIPv4, IPv6, ICMP: routing2 Data linkEthernet, Wi-Fi, ARP: MAC1 Physicalcopper, fibre, radio: bits and volts5 Applicationabsorbs OSI 5, 6, 74 Transport3 Network2 Data link1 PhysicalApplicationTransportInternetLinkmessage / datasegment (TCP)datagram (UDP)packetframebits / symbolsWarning colour = OSI layers 5 and 6 are a classification, not separate software in real stacks.Brand colour = the two layers a developer's code touches through sockets (L4) and routes (L3).
#LayerWhat it really containsReal-world protocolsFiction level
7ApplicationThe protocols programs speak: requests, methods, recordsHTTP, DNS, SMTP, IMAP, SSH, gRPC, MQTTReal
6PresentationEncoding, compression, encryption, serializationTLS records, UTF-8, JSON, Protobuf, gzipFiction: done by libraries inside the app
5SessionDialog control, checkpoints, resumptionCookies, TLS session tickets, RPC session ids, NetBIOS/RPC historicFiction: no separate layer in TCP/IP
4TransportPorts, reliability, ordering, flow and congestion controlTCP, UDP, QUIC, SCTPReal
3NetworkAddressing and routing between networksIPv4, IPv6, ICMP, IPsec, GREReal
2Data linkFraming and addressing on one link, MACEthernet (802.3), Wi-Fi (802.11), ARP, VLAN (802.1Q), PPPReal (split into MAC and LLC in IEEE 802, rarely mentioned)
1PhysicalSignals: voltage, light, radio, connectors1000BASE-T, fibre, 802.11 radioReal, 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-know

In 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 modelTCP/IP RFC 1122 (4)Example you can seeLinux/macOS object
7, 6, 55 ApplicationApplicationGET / HTTP/1.1, DNS questionthe process
44 TransportTransportTCP SYN, UDP datagram, portssocket, ss, netstat
33 NetworkInternetIPv4 header, TTL, routingrouting table, ip route
22 Data linkLinkEthernet header, ARPinterface, neighbour table
11 PhysicalLinklink light, radioNIC, 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-know

In 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.

One GET request, wrapped layer by layer (sender side)L7 messageHTTP request: 56 bytes of textL4 segmentTCP 20payload 56L3 packetIPv4 20TCP 20payload 56L2 frameEth 14IPv4 20TCP 20payload 56FCS 4tcpdump shows 110 bytes (14 + 20 + 20 + 56); the 4-byte FCS is stripped by the NIC.IP packet = up to MTU 1500 bytes (20 IP + 20 TCP + up to 1460 data)TCP payload per segment = MSS 1460 (MTU 1500 - 20 - 20)
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 FCS

MTU, 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.

ItemValueWhere it is set
Ethernet II header14 bytes (6 + 6 + 2)Link layer
Ethernet payload46 to 1500 bytes (padded to 46 if shorter, per RFC 894)Link layer
Ethernet FCS4 bytesNIC hardware
IPv4 header20 bytes without options, up to 60IHL field, in 32-bit words
TCP header20 bytes without options, up to 60Data Offset field, in 32-bit words
UDP header8 bytesfixed
MSS on Ethernet/IPv41460TCP option in SYN
Default MSS if no option arrives536 (576 - 40), IPv4RFC 9293
macOS net.inet.tcp.mssdflt512 (measured on this machine)sysctl
Loopback MTU16384 on macOS lo0 (measured), 65536 on Linux lointerface
VPN/tunnel MTU4064 on macOS utun4 here; WireGuard typically 1420interface

Headers decoded from a capture ​

Must-know

In 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.1

Frame 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.
OffsetBytesFieldMeaning
0-5ff ff ff ff ff ffEthernet destinationBroadcast: every host on the link reads it
6-11e6 22 8e ba 6e f0Ethernet sourceMy Wi-Fi MAC (a locally administered, randomised address)
12-1308 06EtherTypeARP
14-1500 01Hardware typeEthernet
16-1708 00Protocol typeIPv4 (same value as the EtherType for IP)
1806Hardware size6 bytes per MAC
1904Protocol size4 bytes per IPv4 address
20-2100 01Opcode1 = request, 2 = reply
22-27e6 22 8e ba 6e f0Sender MACMe
28-310a 54 32 aeSender IP10.84.50.174
32-3700 00 00 00 00 00Target MACUnknown, that is the question
38-410a 54 32 feTarget IP10.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.....
OffsetBytesLayer / fieldMeaning
0-556 ba 6d ec d8 feEthernet dstThe gateway's MAC, not the DNS server's: the next hop
6-11e6 22 8e ba 6e f0Ethernet srcMe
12-1308 00EtherTypeIPv4
1445IP version + IHLVersion 4, IHL 5 words = 20 bytes
1500IP DSCP/ECNBest effort
16-1700 39IP total length57 = 20 IP + 8 UDP + 29 DNS
18-191c 46IP identification7238
20-2140 00Flags + fragment offsetDF set, offset 0
2240TTL64
2311Protocol17 = UDP
24-25a4 1aIP header checksumVerified by tcpdump
26-290a 54 32 aeSource IP10.84.50.174
30-330a 54 32 feDestination IP10.84.50.254 (the resolver)
34-35cf 84UDP source port53124 (ephemeral)
36-3700 35UDP destination port53
38-3900 25UDP length37 = 8 + 29
40-41ab adUDP checksumPseudo-header + segment
42-433a 7bDNS transaction id14971 (matches the reply)
44-4501 00DNS flagsRD = recursion desired
46-4700 01QDCOUNTOne question
48-5300 00 00 00 00 00ANCOUNT, NSCOUNT, ARCOUNTZero in a query
54-6607 example 03 com 00QNAMELength-prefixed labels, ended by a zero byte
67-6800 01QTYPEA (IPv4 address)
69-7000 01QCLASSIN (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                                     ..
OffsetBytesFieldMeaning
0-1356ba6decd8fe e6228eba6ef0 0800EthernetTo the gateway MAC, IPv4 inside
1445IP version/IHL20-byte header
16-1700 34Total length52 = 20 IP + 32 TCP
2240TTL64
2306Protocol6 = TCP
26-290a 54 32 aeSource IPMe
30-3368 14 17 9aDestination IP104.20.23.154 (a public address: the gateway MAC is used, the IP stays)
34-35c8 22Source port51234
36-3700 50Destination port80
38-411a 2b 3c 4dSequence number439041101: the ISN (initial sequence number)
42-4500 00 00 00Acknowledgment0, no ACK flag yet
4680Data offset (high nibble)8 words = 32 bytes: 20 base + 12 of options
4702FlagsSYN (0x02). Others: FIN 0x01, RST 0x04, PSH 0x08, ACK 0x10, URG 0x20
48-49fa f0Window64240
50-5198 85TCP checksumPseudo-header + segment
52-5300 00Urgent pointerUnused
54-5702 04 05 b4Option MSSkind 2, length 4, value 1460
58-5904 02Option SACK permittedkind 4, length 2
6001NOPPadding
61-6303 03 07Option window scalekind 3, length 3, shift 7 (window x 128)
64-6501 01NOP NOPPad 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....
OffsetBytesFieldMeaning
0-13Ethernet14 bytesSame MACs as the SYN
14-33IPv420 bytesTotal length 00 60 = 96 = 20 + 20 + 56
34-53TCP20 bytesData offset 50 = 5 words = 20 bytes, no options
38-411a 2b 3c 4eSequence439041102 = ISN + 1
42-459f 8e 7d 6dAcknowledgmentThe server's ISN + 1
4718FlagsPSH (0x08) + ACK (0x10): push this data, acknowledgment valid
54-10947 45 54 20 2f ...HTTP payloadASCII 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-know

In 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.

Browser / appGateway + resolverAuthoritative DNSWeb server0 parse URL: scheme http, host example.com, port 80, path /1 ARP who-has gateway (L2 broadcast, once)ARP reply: gateway MAC2 DNS query A example.com (UDP 53)recursion on cache miss: root, TLD, authanswer: A 104.20.23.154 + TTL (cached for that long)3 SYN (src port 51234 -> 80), routed hop by hop, NAT at the edgeSYN/ACKACK: connect() returns after one RTT4 TLS ClientHello (https only, +1 RTT with TLS 1.3)ServerHello, certificate, Finished5 GET / HTTP/1.1 Host: example.com (56 bytes)6 HTTP/1.1 200 OK + HTML (several segments)7 render: parse HTML, then new requests for CSS, JS, images (new DNS/TCP/TLS or reuse)Cost model: DNS 1 RTT (or 0 if cached) + TCP 1 RTT + TLS 1 RTT + HTTP 1 RTT + server timeEvery arrow above is re-framed at every router: new L2 header per hop, same IP packet.
StepLayerWhat happensEvidence you can seeTypical cost
0 Parse7Split scheme, host, port, path, query, fragment (RFC 3986). Default port from the scheme (http 80, https 443). The fragment never leaves the browserurl.Parse in Go, parse_url() in PHPmicroseconds
1 Local lookups7Browser DNS cache, OS cache, /etc/hostsscutil --dns, cat /etc/hosts0 ms on a hit
2 DNS query7 over 4The 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 TTLdig example.com, tcpdump udp port 530-100 ms+
3 Route decision3The kernel picks the interface and next hop from the routing table: on-link destination uses its own MAC, anything else uses the default gatewayroute -n get, ip route getmicroseconds
4 ARP2Find the next hop's MAC if not cachedarp -an, ip neigh1 LAN RTT, once
5 TCP handshake4SYN, SYN/ACK, ACK; connect() returns after one RTTtcpdump 'tcp[tcpflags] & tcp-syn != 0', curl -w %{time_connect}1 RTT
6 TLS (https only)4.5 / 6ClientHello, ServerHello, certificate, Finished; TLS 1.3 adds 1 RTT, TLS 1.2 adds 2 RTTopenssl s_client, TLS in practice1-2 RTT
7 HTTP request7GET / HTTP/1.1, Host: header selects the sitecurl -v, ncRTT/2 to reach the server
8 Server work7App code, database, templatestime_starttransfer - time_connectwhatever your code costs
9 Response7 / 4Headers, then body in many segments; TCP slow start limits the first flightscurl -w %{time_total}1 RTT + transfer
10 Render7Parse HTML, discover CSS/JS/images, repeat steps 1-9 per origin (reuse connections when possible)browser DevTools Network tabtens 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-know

In 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.

LayerAddressExampleSizeScopeWho assigns itChanges at each hop?
7URL / host namehttp://example.com/a?b=1textglobalthe site owner, DNSno
4Port80, 5123416 bitsone hostservice (well-known) or kernel (ephemeral)no (unless PAT rewrites it)
3IPv4 address104.20.23.15432 bitsglobal (or private)operator, DHCP, ISPno (unless NAT rewrites it)
3IPv6 address2606:4700::6814:179a128 bitsglobal or link-localSLAAC, DHCPv6, operatorno
2MAC address56:ba:6d:ec:d8:fe48 bitsone linkNIC vendor (or randomised)yes, every hop
LayerPDU nameHeaderMaximum
7message, data, request/responseprotocol specificunlimited (streams)
4 TCPsegment20-60 bytesMSS (1460) of payload per segment
4 UDPdatagram8 bytes65507 payload bytes theoretical, in practice below the MTU
3packet (IPv4 also "datagram")20-60 bytes65535 total, limited by the path MTU
2frame14 bytes + 4 FCS1514 bytes without FCS (standard)
1bit, symbolnonen/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 ​

Important

In 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.

DeviceLayerReadsDecides byReal-world example
Hub / repeater1nothingrepeats bits on all portsobsolete
Switch / bridge2Ethernet dst MACMAC table (learns source MACs per port)office switch, Linux bridge, Docker docker0
Router3IP dstlongest-prefix match in the routing tablehome router, AWS route table, Linux with ip_forward=1
L3 switch2 + 3MAC and IPboth, in hardwaredata-centre top-of-rack
Firewall (stateless, ACL)3 / 4IP and portsrule list per packetAWS network ACL
Firewall (stateful)3 / 4IP, ports, connection stateconntrack tableiptables, nftables, AWS security group
NAT gateway3 / 4IP and portsrewrites addresses, tracks flowshome router, AWS NAT Gateway, Kubernetes egress
L4 load balancer4IP and portpicks a backend per connectionAWS NLB, HAProxy mode tcp, kube-proxy, IPVS
L7 proxy / load balancer7HTTP method, host, path, headersroutes per requestNGINX, Envoy, AWS ALB, Traefik, HAProxy mode http
WAF7HTTP contentrules over request contentCloudflare WAF, ModSecurity
VPN gateway3IPencapsulates IP in IP/UDPWireGuard, IPsec

Where developers meet each layer ​

Must-know

In 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 useLayerWhat it really isWhat it cannot see
net.Dial, fsockopen, socket()4A kernel socket: a TCP byte stream or UDP datagramsHTTP, messages, framing
HTTP client / server, REST, GraphQL7Text or binary messages over a socketMACs, routes, packet loss
gRPC7 over 4HTTP/2 frames carrying Protobufper-message routing at an L4 balancer
TLS4.5 / 6Records encrypted over a TCP streamnothing on the wire except the SNI and sizes
Docker bridge network2 / 3A Linux software bridge (docker0), a veth pair per container, NAT for outbound trafficHTTP
Docker published port -p 8080:803 / 4A DNAT rule: host port 8080 to container IP port 80the request body
Kubernetes Service (ClusterIP)4Virtual IP and port, DNAT to a pod chosen per connection by kube-proxyHTTP paths, headers
Kubernetes Ingress / Gateway7An HTTP reverse proxy (NGINX, Envoy) configured by objects
Load balancer, L44Forwards connections or packets; backends see the same TCP byteswhich URL was requested
Load balancer, L77Terminates the client connection, opens a new one to a backendnothing: it parses it all (costly)
VPN (WireGuard, IPsec)3A virtual interface (wg0, utun) that encapsulates IP packets inside UDPapplication meaning
SSH tunnel ssh -L4 over 7A TCP stream carried inside another TCP stream
ICMP ping3IP packets with protocol 1 (echo request/reply); no portports, services
CDN7Distributed HTTP caches reached via DNS or anycast
Database connection4 / 7A 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:

sql
-- 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 ​

Important

In 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.

MiddleboxWhat it doesWhat it breaksSymptom
NAT / PATRewrites IPs and ports, keeps a flow tableInbound connections, protocols that embed IPs (FTP active mode, SIP)"works outbound, not inbound"; idle connections silently dropped after a timeout
Stateful firewallTracks flows, drops unknown onesLong-idle connections, asymmetric routingConnection hangs after minutes of silence
L7 proxy / CDNTerminates and re-opens connectionsClient IP visibility, WebSockets, long polls, UpgradeApp sees the proxy's IP; use X-Forwarded-For / PROXY protocol
Path MTU black holeDrops ICMP "fragmentation needed"Large packets onlySmall requests fine, big uploads hang
TLS-inspecting boxTerminates TLS, re-signsCertificate pinning, mTLSUnknown CA errors
TUN-mode proxy (this machine)Accepts the TCP handshake locallyLatency measurements, DNS truth0.3 ms "handshake" to a server 150 ms away
Carrier-grade NATShares one public IP among subscribersPort forwarding, peer-to-peerYou 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 ​

Important

In 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.

ComponentLayerFormulaTypical sizeHow to reduce
Propagation delay1distance / signal speed (about 200,000 km/s in fibre, two-thirds of c)5 ms per 1000 km one wayMove the server closer (CDN, region)
Serialization delay1/2frame size / link rate1500 B on 100 Mbit/s = 120 us; on 1 Gbit/s = 12 usFaster link
Queuing delay2/3time waiting in a router/switch buffer0 to hundreds of ms (bufferbloat)Less load, AQM (CoDel, fq_codel)
Processing delay2/3lookup, firewall, NATmicrosecondsHardware offload
Handshake cost4RTTs before data: TCP 1, TLS 1.3 +11 RTT eachKeep-alive, connection pools, TLS 1.3 0-RTT, HTTP/3
DNS cost70 on cache, 1 RTT to the resolver, more on recursion0-200 msTTLs, local caches, dns-prefetch
Server time7application work1 ms to secondsYour 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 ms

Measured 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-know

In 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.

QuestionLinux (iproute2)macOSNotes
List interfaces and stateip linkifconfig -l, ifconfigBoth show MTU and MAC
Addressesip addr (ip -br a)ifconfig en0, ipconfig getifaddr en0
Routing tableip route, ip route get 8.8.8.8netstat -rn, route -n get 8.8.8.8ip route get shows interface, source and gateway chosen
Neighbour (ARP/NDP) cacheip neigharp -an, ndp -an
Socketsss -tulpn, ss -tannetstat -an -p tcp, lsof -iTCP -sTCP:LISTEN -nPss is faster and shows timers and TCP info
Packet capturetcpdump -i eth0, tcpdump -i anytcpdump -i en0, one interface at a timeNeeds root or CAP_NET_RAW / read access to /dev/bpf*
GUI captureWireshark, tsharkWireshark (ChmodBPF helper)
Reachabilityping, traceroute, mtrping, traceroute (BSD flags differ)
DNSdig, resolvectl statusdig, scutil --dns
Per-connection timersss -tinot availableRTT, cwnd, retransmits
Link statisticsip -s link, ethtool -S eth0netstat -I en0, netstat -s

Interface names ​

NameOSMeaning
lo / lo0Linux / macOSLoopback, 127.0.0.1 and ::1; never leaves the machine
eth0, ens5, enp3s0LinuxEthernet; the second form is "predictable naming" by the udev rule (firmware index, PCI slot)
wlan0, wlp2s0LinuxWi-Fi
en0, en1macOSEthernet or Wi-Fi (on this Mac en0 is Wi-Fi)
docker0, br-3f2a...LinuxDocker default and user-defined bridges
veth1a2b3cLinuxOne end of a virtual Ethernet pair, the other end is eth0 inside a container
cni0, flannel.1, cali*, cilium_*LinuxKubernetes CNI interfaces
tun0, wg0LinuxTunnel interfaces: OpenVPN, WireGuard
utun0 ... utun4macOSTunnel interfaces for VPNs, iCloud Private Relay, proxies (this machine: utun4 is the default route)
awdl0, llw0, ap1macOSApple Wireless Direct Link (AirDrop), low-latency WLAN, access point
bridge0macOSThunderbolt/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 16384

The 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:80

Loopback versus real interfaces ​

PropertyLoopback (lo, lo0)Real NIC (eth0, en0)
Address127.0.0.0/8, ::1assigned (DHCP, static)
Layer 2none: 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
MTU16384 (macOS here), 65536 (Linux)1500 typical
Leaves the machinenever; the kernel hands the packet to itselfyes
Firewallusually bypassedapplies
Bind effect127.0.0.1:8080 reachable only locally0.0.0.0:8080 reachable from the network
Misleading whentesting 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, sends

The 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 3

Checksums and where they live ​

LayerCheckCoversComputed by
2Ethernet FCS (CRC-32)whole frameNIC, stripped before capture
3IPv4 header checksumIP header only (IPv6 has none)each router recomputes after TTL-1
4TCP / UDP checksumpseudo-header + segmentend hosts
7application (e.g. SHA-256 in downloads, TLS MACs)payloadendpoints (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 / symptomLayerMeaning
No route to host (EHOSTUNREACH)3 / 2No route, or ARP got no answer
Network is unreachable (ENETUNREACH)3No route matches, not even a default
Connection refused (ECONNREFUSED)4A RST came back: host reachable, nothing listening (or firewall REJECT)
Connection timed out (ETIMEDOUT)3 / 4No reply at all: dropped by a firewall, wrong IP, or host down
Connection reset by peer (ECONNRESET)4RST in the middle of a connection
Name or service not known / Could not resolve host7 (DNS)The resolver returned NXDOMAIN or failed
ICMP type 3 code 43Fragmentation needed and DF set (Path MTU)
ICMP type 113TTL exceeded in transit (traceroute)
HTTP 502 / 5047A proxy could not reach or wait for the upstream

Solving the classic problems ​

ProblemLayerFast diagnosisFix
"Site does not load"anyping IP, dig name, curl -v in that orderThe first failing step names the layer
Name resolves wrong or slow7dig +trace, scutil --dns / resolvectl statusFix the resolver, TTL or /etc/hosts
Connection refused4ss -tlnp, lsof -iTCP -sTCP:LISTENStart the service, bind the right address, open the port
Connection timeout3/4traceroute, tcpdump shows SYNs with no SYN/ACKFirewall, security group, route
Large transfers hang, small ones work3ping -D -s 1472Fix MTU/MSS clamping, allow ICMP type 3
Container cannot reach another2/3ip addr, ip route inside; docker network inspectSame network, correct name
Works on localhost, not remotely4ss -tln shows 127.0.0.1:portBind 0.0.0.0
Client IP is always the proxy3/7log X-Forwarded-ForTrust the header from known proxies; PROXY protocol for L4

Reading a capture the right way ​

  1. Start with tcpdump -nn (no DNS or service name lookups, no extra packets from your own capture).
  2. Filter early: host, port, tcp[tcpflags], udp port 53.
  3. Read flags first: [S] SYN, [S.] SYN/ACK, [.] ACK, [P.] data, [F.] FIN, [R] RST.
  4. Compare timestamps between SYN and SYN/ACK for the handshake RTT.
  5. Only then dump bytes with -XX or open the file in Wireshark.
FilterShows
tcpdump -nn -i en0 host 104.20.23.154All traffic to or from one host
tcpdump -nn 'tcp[tcpflags] & tcp-syn != 0'Every SYN and SYN/ACK
tcpdump -nn udp port 53DNS
tcpdump -nn -e arpARP with MAC addresses
tcpdump -nn -s0 -w out.pcapSave full packets to a file for Wireshark
tcpdump -r out.pcap -XXRead a file (no root needed)

Choosing ​

You want to...Work at layerToolReason
Prove a host is alive3pingICMP needs no open port, but may be filtered
Prove a service accepts connections4nc -vz host port, curl -vCompletes a real handshake
Prove the application answers correctly7curl -v, HTTP clientChecks status, headers, body
See who is talking to whom4ss, lsof -i, netstatSockets and processes
See exact bytes and timing2-7tcpdump, WiresharkGround truth
Pick a load balancer for TCP/TLS passthrough4NLB, HAProxy tcp, IPVSCheap, protocol-agnostic
Route by URL, header, cookie7ALB, NGINX, EnvoyNeeds HTTP parsing
Reach a private network3WireGuard, IPsecRoutes whole subnets
Reach one remote port4ssh -LOne 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 ​

ScaleNetwork pictureTypical change
1x: one serverPublic IP, DNS A record, Nginx on 443Keep-alive, HTTP/2, TLS 1.3
10x: several app serversL7 load balancer, private subnet, security groupsHealth checks, connection draining, shared sessions
100x: many servicesL4 in front of L7, service discovery, mesh, mTLSConnection pooling per upstream, timeouts per layer
Multi-regionGeoDNS or anycast, CDN, cross-region replicationEdge caching, async replication, regional failover
Very largeAnycast, 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.

go
// 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)
	}
}
go
// 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 ​

go
// 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, HEAD

The 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):

go
// 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 bytes

HTTP/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.

go
// 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.994292ms

Building 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.

go
// 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 ​

go
// 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 bytes

Reading 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.

go
// 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=56B

Raw 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
//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
<?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
<?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
<?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
<?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.

  1. 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.
  2. Capture one curl and annotate every packet.
    # 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 -tt
    Expected shape (documentation-range addresses; yours differ):
    1  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.] / [.]
    Annotate: 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 final F packets close the connection. With -e add MACs: the destination MAC is always your gateway's, never the server's.
  3. 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, ttfb 3.16 s, 0.278 s, 1.011 s. Subtract: ttfb - tcp is request, server time and response; tcp alone is one RTT. Compare with the Go program and with ping.
  4. Show the MTU with ping -D -s. -D sets DF (macOS; Linux uses -M do), -s sets the ICMP payload size. Packet size = payload + 8 ICMP + 20 IP. For MTU 1500 the largest payload is 1500 - 28 = 1472.
    $ 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 loss
    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: sendto: Message too long followed by Request timeout for icmp_seq 0: the local kernel refuses to send a DF packet that does not fit the interface MTU. Linux prints ping: 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.
  5. 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.
  6. Raw HTTP by hand. printf 'GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n' | nc example.com 80. Remove Host: and watch the server answer 400 (HTTP/1.1 requires the header).
  7. Find which layer fails. ping -c1 10.84.50.254 (L3 to gateway) then dig example.com (L7 DNS) then nc -vz example.com 80 (L4) then curl -v http://example.com/ (L7). The first command that fails names the layer.

Common misconceptions ​

BeliefReality
The internet uses the OSI modelIt uses TCP/IP; OSI supplies the vocabulary
Every packet passes through seven layersApplication, 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 addressesOnly NAT does; ordinary routers change the MAC and the TTL
The destination MAC is the server'sIt is the next hop's; the server's MAC is never seen by a remote client
ping works, so the service worksICMP only proves L3; the port and the app are separate checks
TCP delivers messagesIt delivers a byte stream; boundaries are your job
Bigger bandwidth means lower latencyPropagation delay is fixed by distance
127.0.0.1 and my LAN IP are the sameLoopback is unreachable from other hosts
A Kubernetes Service is a processIt is a virtual IP implemented by NAT rules
Packet captures on the sender show true checksumsOffload can leave them blank until the NIC fills them in
A VPN works at the HTTP levelIt carries IP packets, so every protocol goes through it

Cheat sheet ​

TopicWhat to remember
Layer jobsL2 same link (MAC), L3 between networks (IP), L4 which program (port), L7 the message
Header sizesEthernet 14, IPv4 20, TCP 20, UDP 8; add options by Data Offset / IHL
Frame budget1500 MTU = 20 IP + 20 TCP + 1460 MSS payload; frame 1514 without FCS
EtherTypes0x0800 IPv4, 0x0806 ARP, 0x86DD IPv6
IP protocol numbers1 ICMP, 6 TCP, 17 UDP
URL journeyparse, DNS, TCP, TLS, HTTP, response, render; costs 1 RTT per round trip stage
Who rewrites whatRouter: MAC and TTL; NAT: IP and port; proxy: the whole connection
End-to-endDo correctness at the endpoints; middleboxes are exceptions that cause bugs
Latencypropagation + serialization + queuing + processing; only distance fixes the first
refused vs timeoutrefused = a RST came back (L4 alive); timeout = silence (drop or no route)
Linux toolsip link/addr/route/neigh, ss -tulpn, tcpdump -nn, dig
macOS toolsifconfig, netstat -rn, arp -an, lsof -i, scutil --dns, tcpdump -i en0
Capture without roottcpdump -r file.pcap, Wireshark, gopacket with pcapgo
MTU testping -D -s 1472 (macOS), ping -M do -s 1472 (Linux)
Loopbackno MAC, no ARP, huge MTU, never leaves the host

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
OSI modelSeven-layer reference model from ISO; mostly a vocabulary
TCP/IP modelFour-layer Internet model: link, internet, transport, application (RFC 1122)
LayerA level of the stack offering a service to the layer above
EncapsulationWrapping a PDU as the payload of the next lower layer
DecapsulationRemoving a layer's header on the way up
PDUProtocol data unit: frame, packet, segment, datagram, message
FrameLayer 2 PDU, e.g. an Ethernet frame
PacketLayer 3 PDU, e.g. an IP packet
SegmentTCP PDU
DatagramUDP PDU (and the IPv4 name of a packet in RFC 791)
MAC address48-bit link-layer address, meaningful on one link
EtherType2-byte field naming the payload protocol (0x0800 IPv4, 0x0806 ARP)
FCSFrame check sequence: Ethernet CRC-32 trailer
IPv4 header / IHL20-byte network header; IHL gives its length in 32-bit words
TTLHop limit decremented by each router; 0 drops the packet
MTULargest IP packet a link carries (1500 on Ethernet)
MSSLargest TCP payload per segment (1460 on Ethernet/IPv4)
Path MTU DiscoveryLearning the smallest MTU on a path through ICMP "fragmentation needed" (RFC 1191)
DF bitDon't Fragment flag in the IPv4 header
ARPAddress Resolution Protocol: IPv4 address to MAC (RFC 826)
NDPNeighbor Discovery Protocol: ARP's job in IPv6
Three-way handshakeSYN, SYN/ACK, ACK opening a TCP connection
ISNInitial sequence number chosen in the SYN
Window scaleTCP option multiplying the advertised window
SACKSelective acknowledgment option
Ephemeral portShort-lived client-side port chosen by the kernel
SocketKernel object identified by protocol, local address and port, remote address and port
SwitchLayer 2 device forwarding by MAC
RouterLayer 3 device forwarding by IP
NAT / PATRewriting IP addresses / addresses and ports
MiddleboxIntermediary doing more than IP forwarding (RFC 3234)
End-to-end principlePlace correctness functions at the endpoints (Saltzer et al.)
Fate-sharingKeep connection state only in endpoints (RFC 1958)
LoopbackVirtual interface for local traffic, 127.0.0.1 and ::1
vethLinux virtual Ethernet pair connecting a container to a bridge
TUN interfaceVirtual L3 interface used by VPNs and proxies
pcapFile format for captured packets
BPFPacket filter facility used by tcpdump on BSD/macOS
Propagation delayTime for a signal to travel the distance
Serialization delayTime to put all bits of a frame on the wire
Queuing delayTime spent waiting in a buffer
RTTRound-trip time
Offload (TSO, GSO, GRO)NIC or kernel features that batch or split packets
AnycastSame 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.

Built by Morteza Negahi