The Network Stack
When a browser calls connect() and then send(), a lot happens before a single bit leaves the network card: the kernel picks a route and a source port, builds TCP, IP and Ethernet headers, keeps a copy of the data for retransmission, and hands a buffer to the driver by DMA. This lesson follows data through the operating system's network stack, shows the TCP connection state machine that both Linux and Windows implement, and compares the pieces and tools of the two systems.
Layers inside the OS
user mode application: browser, curl, ssh, nginx
socket API: socket() bind() listen() accept() connect() send() recv()
(Windows: Winsock, ws2_32.dll -> mswsock.dll)
============================ system call ==============================
kernel socket layer Linux: net/socket.c Windows: afd.sys
transport TCP, UDP (QUIC lives in user space or msquic)
network IPv4 / IPv6, routing, firewall hooks
Linux: netfilter (nftables) Windows: WFP
link ARP / neighbour discovery, bridging, VLANs
Linux: net_device + qdisc Windows: NDIS
NIC driver ring buffers, DMA, interrupts / NAPI polling
======================================================================
hardware network card -> cable / Wi-FiWindows implements TCP/IP in tcpip.sys; programs reach it through Winsock and the Ancillary Function Driver afd.sys, which gives sockets their file-like handles. Network cards are driven through NDIS (Network Driver Interface Specification) miniport drivers, and the Windows Filtering Platform (WFP) lets the firewall and security tools inspect traffic. In Linux the whole stack lives in the kernel's net/ tree; netfilter hooks power nftables/iptables, and eBPF/XDP programs can process packets right at the driver.
Sockets: the same API on both systems
The Berkeley sockets API from 1983 Unix is what both systems offer. A server and a client use these calls:
server client
socket() socket()
bind(port 8080)
listen()
accept() <---- handshake ---- connect(server:8080)
recv() <------ data ------- send()
send() ------- data ------> recv()
close() <----- FIN/ACK ----> close()Winsock adds WSAStartup() at the beginning and calls a socket a SOCKET handle instead of an int file descriptor, but the shape is the same. That's why most network code ports easily.
Encapsulation
Each layer wraps the data from the layer above with its own header. On the way out the kernel adds headers; on the way in it strips them and uses the fields to find the right socket:
payload = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
layers = [
("TCP", 20, "src port 51514, dst port 80, seq, ack, flags, window"),
("IPv4", 20, "src 192.168.1.20, dst 93.184.215.14, TTL 64, protocol 6"),
("Ethernet", 14, "dst MAC (router), src MAC (our NIC), type 0x0800"),
]
size = len(payload)
print(f"{'HTTP data':<10} {size:>4} bytes")
for name, header, fields in layers:
size += header
print(f"{'+ ' + name:<10} {size:>4} bytes header {header:>2}: {fields}")
overhead = size - len(payload)
print(f"header overhead: {overhead} bytes ({overhead / size:.0%} of the frame)")HTTP data 37 bytes
+ TCP 57 bytes header 20: src port 51514, dst port 80, seq, ack, flags, window
+ IPv4 77 bytes header 20: src 192.168.1.20, dst 93.184.215.14, TTL 64, protocol 6
+ Ethernet 91 bytes header 14: dst MAC (router), src MAC (our NIC), type 0x0800
header overhead: 54 bytes (59% of the frame)
For a tiny request the headers are a big share; for a full 1500-byte packet they are only a few percent. Modern NICs take work off the CPU with offloads: checksum calculation, TSO/LSO (the kernel hands over one 64 KiB chunk and the card splits it into packets) and receive-side scaling (RSS, spreading flows over cores).
Finding the right socket: ports and the 4-tuple
A host has one IP stack but thousands of sockets. An incoming TCP segment is delivered to the socket whose 4-tuple (local IP, local port, remote IP, remote port) matches; if none matches, a listening socket on that local port gets it (a new connection), and otherwise the kernel answers with a reset (RST).
sockets = [
{"local": ("0.0.0.0", 443), "remote": None, "state": "LISTEN", "owner": "nginx"},
{"local": ("10.0.0.5", 443), "remote": ("203.0.113.9", 50100), "state": "ESTABLISHED", "owner": "nginx"},
{"local": ("10.0.0.5", 443), "remote": ("198.51.100.7", 61000),"state": "ESTABLISHED", "owner": "nginx"},
{"local": ("127.0.0.1", 5432), "remote": None, "state": "LISTEN", "owner": "postgres"},
]
def demux(dst_ip, dst_port, src_ip, src_port):
for s in sockets: # exact 4-tuple first
if s["remote"] == (src_ip, src_port) and s["local"] == (dst_ip, dst_port):
return f"{s['owner']} connection {s['state']}"
for s in sockets: # then a listener
ip, port = s["local"]
if s["state"] == "LISTEN" and port == dst_port and ip in ("0.0.0.0", dst_ip):
return f"{s['owner']} listener: new connection"
return "no socket: reply with RST"
tests = [("10.0.0.5", 443, "203.0.113.9", 50100), ("10.0.0.5", 443, "192.0.2.1", 40000),
("10.0.0.5", 5432, "192.0.2.1", 40001), ("127.0.0.1", 5432, "127.0.0.1", 39000),
("10.0.0.5", 22, "192.0.2.1", 40002)]
for dst_ip, dst_port, src_ip, src_port in tests:
print(f"{src_ip}:{src_port} -> {dst_ip}:{dst_port} => {demux(dst_ip, dst_port, src_ip, src_port)}")203.0.113.9:50100 -> 10.0.0.5:443 => nginx connection ESTABLISHED
192.0.2.1:40000 -> 10.0.0.5:443 => nginx listener: new connection
192.0.2.1:40001 -> 10.0.0.5:5432 => no socket: reply with RST
127.0.0.1:39000 -> 127.0.0.1:5432 => postgres listener: new connection
192.0.2.1:40002 -> 10.0.0.5:22 => no socket: reply with RST
Note the third line: PostgreSQL listens on 127.0.0.1 only, so a connection to the public address is refused. Binding to the loopback address is the simplest way to keep a service private.
The TCP state machine
TCP is a connection protocol: both ends keep a state for each connection, and segments with the SYN, ACK and FIN flags move them between states. The three-way handshake opens a connection; four segments (two FIN/ACK pairs) close it. The side that closes first waits in TIME_WAIT (typically 60 s on Linux, 120 s by default on Windows) so that stray old segments can't confuse a new connection on the same ports.
TRANSITIONS = { # (state, event) -> (new state, segment sent)
("CLOSED", "connect"): ("SYN_SENT", "SYN"),
("LISTEN", "rcv SYN"): ("SYN_RCVD", "SYN+ACK"),
("SYN_SENT", "rcv SYN+ACK"): ("ESTABLISHED", "ACK"),
("SYN_RCVD", "rcv ACK"): ("ESTABLISHED", None),
("ESTABLISHED", "close"): ("FIN_WAIT_1", "FIN"),
("ESTABLISHED", "rcv FIN"): ("CLOSE_WAIT", "ACK"),
("FIN_WAIT_1", "rcv ACK"): ("FIN_WAIT_2", None),
("CLOSE_WAIT", "close"): ("LAST_ACK", "FIN"),
("FIN_WAIT_2", "rcv FIN"): ("TIME_WAIT", "ACK"),
("LAST_ACK", "rcv ACK"): ("CLOSED", None),
}
state = {"client": "CLOSED", "server": "LISTEN"}
other = {"client": "server", "server": "client"}
pending = [] # segments in flight: (to, flags)
def event(side, ev):
new, send = TRANSITIONS[(state[side], ev)]
print(f"{side:<6} {state[side]:<11} --{ev:<11}--> {new}" + (f" sends {send}" if send else ""))
state[side] = new
if send:
pending.append((other[side], send))
def deliver():
to, flags = pending.pop(0)
event(to, "rcv " + flags)
event("client", "connect") # SYN
deliver(); deliver(); deliver()
print("-- data flows both ways --")
event("client", "close") # FIN
deliver(); deliver()
event("server", "close") # FIN
deliver(); deliver()
print(state)client CLOSED --connect --> SYN_SENT sends SYN
server LISTEN --rcv SYN --> SYN_RCVD sends SYN+ACK
client SYN_SENT --rcv SYN+ACK--> ESTABLISHED sends ACK
server SYN_RCVD --rcv ACK --> ESTABLISHED
-- data flows both ways --
client ESTABLISHED --close --> FIN_WAIT_1 sends FIN
server ESTABLISHED --rcv FIN --> CLOSE_WAIT sends ACK
client FIN_WAIT_1 --rcv ACK --> FIN_WAIT_2
server CLOSE_WAIT --close --> LAST_ACK sends FIN
client FIN_WAIT_2 --rcv FIN --> TIME_WAIT sends ACK
server LAST_ACK --rcv ACK --> CLOSED
{'client': 'TIME_WAIT', 'server': 'CLOSED'}
You can watch these states on a real machine. On Linux ss reads them from the kernel (sample output — yours will differ):
ada@ubuntu:~$ ss -tan
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 4096 127.0.0.1:5432 0.0.0.0:*
LISTEN 0 511 0.0.0.0:80 0.0.0.0:*
ESTAB 0 0 192.168.1.20:51514 93.184.215.14:443
TIME-WAIT 0 0 192.168.1.20:51502 93.184.215.14:443On Windows, netstat -ano or PowerShell's Get-NetTCPConnection (sample output — yours will differ):
PS C:\Users\ada> Get-NetTCPConnection -State Listen, Established |
>> Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess
LocalAddress LocalPort RemoteAddress RemotePort State OwningProcess
------------ --------- ------------- ---------- ----- -------------
0.0.0.0 135 0.0.0.0 0 Listen 1196
0.0.0.0 445 0.0.0.0 0 Listen 4
192.168.1.20 51514 93.184.215.14 443 Established 9120(Port 445, SMB file sharing, is owned by PID 4, the System process, because the SMB server runs in the kernel.)
Kernel tables as text
The Linux kernel publishes its socket table in /proc/net/tcp, with addresses as little-endian hexadecimal and states as numbers (0A = LISTEN, 01 = ESTABLISHED, 06 = TIME_WAIT). Tools such as ss and netstat decode it. This script decodes two sample lines the same way:
cat > tcp.txt <<'EOF'
sl local_address rem_address st
0: 0100007F:1538 00000000:0000 0A
1: 1401A8C0:C93A 0ED7B85D:01BB 01
EOF
decode_ip() { # little-endian hex -> dotted quad
local h=$1
printf '%d.%d.%d.%d' "0x${h:6:2}" "0x${h:4:2}" "0x${h:2:2}" "0x${h:0:2}"
}
tail -n +2 tcp.txt | while read -r _ local remote st; do
lip=${local%:*}; lport=${local#*:}; rip=${remote%:*}; rport=${remote#*:}
case $st in 0A) name=LISTEN ;; 01) name=ESTABLISHED ;; *) name=$st ;; esac
printf '%-20s %-20s %s\n' "$(decode_ip "$lip"):$((16#$lport))" "$(decode_ip "$rip"):$((16#$rport))" "$name"
done127.0.0.1:5432 0.0.0.0:0 LISTEN
192.168.1.20:51514 93.184.215.14:443 ESTABLISHED
Configuration and tools
| Task | Linux | Windows |
|---|---|---|
| Show addresses | ip addr |
ipconfig /all, Get-NetIPAddress |
| Routing table | ip route |
route print, Get-NetRoute |
| Open sockets | ss -tulpn |
netstat -ano, Get-NetTCPConnection |
| DNS lookup | dig, resolvectl query |
nslookup, Resolve-DnsName |
| Test a port | nc -zv host 443 |
Test-NetConnection host -Port 443 |
| Firewall | nft, ufw, firewalld |
Windows Defender Firewall, New-NetFirewallRule |
| Packet capture | tcpdump, Wireshark |
pktmon, Wireshark |
| Kernel tunables | sysctl net.ipv4.* |
netsh int tcp, registry |
Learn more: Devices & I/O · Inter-Process Communication · Linux vs Windows
Test yourself
Which three segments make up the TCP handshake?
- SYN, SYN+ACK, ACK
- SYN, ACK, FIN
- HELLO, ACK, READY
- FIN, ACK, FIN
A server socket is bound to 127.0.0.1:5432. What happens to a connection from another machine to the server's LAN address on port 5432?
- It is accepted
- It is refused (RST), because no socket listens on that address and port
- It is forwarded to localhost
- It waits in TIME_WAIT
Which side of a TCP connection ends up in TIME_WAIT?
- The side that closes first
- The side that closes last
- Always the server
- Always the client