TCP/IP Networking
— complete guide
Everything from network models to firewalls. Each section explains the purpose before the details, with interactive visuals throughout.
Network models
Models break networking into layers so engineers work on one piece without understanding all others. Two matter: OSI (theoretical) and TCP/IP (practical).
A layered model lets a Wi-Fi engineer work on signals without knowing HTTP, and a web developer write apps without knowing signal propagation. Each layer has one job and a defined interface to the layers above and below.
OSI & TCP/IP layers
Each layer solves exactly one problem. Click any row to understand what problem that layer was invented to solve.
Layers don’t need to know what’s inside the layers above or below them. IP doesn’t care that TCP is inside it. TCP doesn’t care that HTTP is inside it. This ignorance is intentional — it’s what lets you swap Ethernet for Wi-Fi without changing a single line of application code.
| # | Layer | TCP/IP | PDU | Key protocols |
|---|---|---|---|---|
| 7 | Application | Application | Message | HTTP, DNS, SMTP, FTP |
| 6 | Presentation | Application | Message | TLS/SSL, JPEG, ASCII |
| 5 | Session | Application | Message | NetBIOS, RPC |
| 4 | Transport | Transport | Segment/Datagram | TCP, UDP |
| 3 | Network | Internet | Packet | IP, ICMP, ARP |
| 2 | Data Link | Network access | Frame | Ethernet, Wi-Fi, PPP |
| 1 | Physical | Network access | Bit | Cables, signals, NICs |
Encapsulation
Each layer wraps data with its own header before passing it down. Click any layer to see what it adds and why.
Each layer reads only its own wrapper, strips it, and passes the rest up. The router reads the IP header — not the TCP segment inside. This separation means IPv6 can replace IPv4 without changing TCP or HTTP.
IPv4 addresses
Every device needs a unique logical address. IPv4 provides a 32-bit address — four 0–255 numbers separated by dots.
MAC addresses identify hardware and can’t be organised hierarchically. IP addresses are logical and assignable — they can be grouped by network prefix, enabling routers to forward data efficiently across the entire internet.
| Class | Range | Mask | Purpose |
|---|---|---|---|
| A | 1–126.x.x.x | /8 | Large networks |
| B | 128–191.x.x.x | /16 | Medium networks |
| C | 192–223.x.x.x | /24 | Small networks |
| D | 224–239.x.x.x | N/A | Multicast |
Subnetting
Subnetting divides a network into smaller ones. A subnet mask tells you which bits identify the network and which identify the host.
Without subnetting, every device in a company would be on one giant broadcast domain — every ARP and discovery packet would hit every machine. Subnetting creates isolated segments, improves performance, and adds security boundaries between departments.
Network: 192.168.1.0 ← not assignable
First host: 192.168.1.1
Last host: 192.168.1.254
Broadcast: 192.168.1.255 ← not assignable
Hosts: 254 usable
IPv6
IPv4’s 4 billion addresses ran out. IPv6 provides 340 undecillion — enough for every grain of sand to have billions of addresses.
IPv4 was designed in 1981 for a small research network. IPv6 solves the exhaustion problem with 128-bit addresses, and also adds built-in IPSec, simpler routing headers, stateless autoconfiguration, and eliminates the need for NAT.
128-bit addresses
Eight groups of four hex digits. e.g. 2001:0db8:85a3::8a2e:0370:7334. Consecutive zero groups compress to ::.
IPSec built in
IPv6 mandates IPSec support. Encryption and authentication are first-class features, not optional add-ons.
No NAT needed
Every device gets a globally unique address. NAT becomes unnecessary — end-to-end connectivity is restored.
SLAAC
Stateless Address Autoconfiguration: devices generate their own IPv6 address from their MAC + network prefix. No DHCP server required.
| Feature | IPv4 | IPv6 |
|---|---|---|
| Address size | 32 bits | 128 bits |
| Total addresses | ~4.3 billion | ~3.4 × 10³⁸ |
| Header size | 20 bytes (min) | 40 bytes (fixed) |
| Notation | Dotted decimal | Hex with colons |
| Fragmentation | Routers & hosts | Source hosts only |
MAC addresses & ARP
IP identifies devices logically. MAC identifies their hardware physically. ARP is the bridge between them.
You know the IP of who you want to reach, but not their MAC. ARP broadcasts “Who has IP X? Tell me your MAC.” — and only the device with that IP replies. The result gets cached, so ARP doesn’t happen for every packet.
MAC structure
48 bits: first 3 bytes = OUI (manufacturer), last 3 bytes = device serial. Burned in at factory. e.g. AA:BB:CC:DD:EE:FF
ARP request
Broadcast to 255.255.255.255: “Who has 192.168.1.1? Tell 192.168.1.5.” Every device on the LAN receives this.
ARP reply
Only the matching device responds: “192.168.1.1 is at AA:BB:CC:11:22:33.” Unicast directly to the requester.
ARP cache
Results cached for a few minutes. Check yours:
arp -a. Stale entries can cause connectivity issues after IP changes.
TCP overview
TCP makes the internet reliable. IP delivers packets to the right machine — TCP ensures they arrive correctly, completely, and in order.
IP is deliberately "dumb" — it routes packets fast and drops them when the network is congested. This is a feature. TCP compensates on top, adding reliability, ordering, and flow control. The separation lets the internet scale: IP doesn't slow down for acknowledgments; TCP handles that at the endpoints.
Connection-oriented
TCP establishes a dedicated connection before data flows. Both sides maintain shared state throughout the session.
Reliable delivery
Every segment is numbered and acknowledged. Nothing is silently dropped — unacknowledged data is retransmitted.
Ordered data
Sequence numbers let the receiver reassemble segments in correct order, even if they arrive out of sequence.
Flow control
The receiver advertises its available buffer (receive window). The sender never overwhelms a slow receiver.
Congestion control
TCP detects network congestion via packet loss and slows transmission. This is why the internet doesn't collapse under load.
Full-duplex
Data flows both ways simultaneously. Each direction has its own sequence numbers and flow control window.
The 3-way handshake
Before data moves, both sides must agree they're ready and synchronise sequence numbers. This 3-step ritual opens every TCP connection.
Two steps only confirm one direction. Three steps confirm both directions and let both sides exchange Initial Sequence Numbers simultaneously. You cannot accomplish this in fewer than three messages.
Client: "I want to connect"
Sends SYN with Initial Sequence Number, e.g. seq=100. Enters SYN_SENT state.
Server: "I hear you, I'm ready too"
Acknowledges (ACK=101) and picks its own ISN (seq=300). Enters SYN_RECEIVED.
Client: "Got it. Connection open."
Acknowledges server's ISN (ACK=301). Both sides enter ESTABLISHED. Data can now flow.
Reliability & ACKs
TCP guarantees every byte arrives exactly once, in order. Sequence numbers and acknowledgments are the machinery behind that promise.
IP may drop, duplicate, or reorder packets at any time. TCP detects all three failure modes: sequence numbers catch ordering and duplicates; ACK numbers catch losses. Anything not confirmed gets retransmitted.
Timeout (RTO)
No ACK within the Retransmission Timeout → sender retransmits. RTO is adaptive and grows with network latency.
Fast retransmit
3 duplicate ACKs = likely loss. Sender retransmits immediately without waiting for timeout — much faster recovery.
SACK
Selective ACK: receiver reports exactly which segments arrived. Sender retransmits only what's missing, not everything from the loss point onward.
Flow control
TCP prevents a fast sender from overwhelming a slow receiver using a receive window advertised by the receiver.
A 10 Gbps server and a phone on slow mobile data have wildly different processing speeds. Without flow control, the server would fill the phone's buffer until packets drop — then TCP retransmits everything anyway, wasting bandwidth. Flow control avoids this entirely.
TCP flags
Single-bit flags in the TCP header tell the receiver what kind of segment this is. They're the vocabulary TCP uses to signal state.
TCP needs to signal many things — open a connection, acknowledge data, close gracefully, abort. Packing these into individual bits in the header means all this signalling adds zero overhead to data segments. The bits are always there anyway.
SYN+ACK → open accepted (step 2)
ACK → data delivery confirmation
PSH+ACK → deliver to app now
FIN+ACK → graceful close
RST+ACK → abrupt reset
Connection teardown
Closing a TCP connection takes 4 steps. Each side must independently signal it's done sending.
TCP is full-duplex — both sides send independently. A FIN from one side is a half-close: "I'm done sending, but I can still receive." The other side might still have data to send. The connection only fully closes when both sides have FIN'd and both FINs are acknowledged.
ESTABLISHED
Both sides communicating normally.
Client → FIN
Client done sending. Enters FIN_WAIT_1. Server can still send data.
Server → ACK
Acknowledges FIN. Client enters FIN_WAIT_2 and waits. Server finishes its remaining data.
Server → FIN
Server done sending. Enters LAST_ACK. Both sides now want to close.
Client → ACK — CLOSED
Client sends final ACK. Waits in TIME_WAIT (2×MSL) before fully closing port.
UDP & TCP comparison
UDP makes the opposite trade-off to TCP: no connection, no guarantees, maximum speed. Choose based on what failure looks like for your use case.
Reliability costs time. Every ACK, retransmit, and handshake adds latency. For a video call, a 200ms delayed packet is worse than a dropped one — the moment is gone. For a file download, a single missing byte is catastrophic. The right protocol depends entirely on whether silence (no ACK) is worse than delay.
DNS — Domain Name System
DNS translates human-readable names into IP addresses. It runs before every other protocol — every web request, email, and API call starts with a DNS lookup.
Computers communicate using IPs (like 93.184.216.34) but humans remember names (like example.com). DNS is the translation layer. It also enables load balancing, failover, CDN routing, and email authentication — it's far more than just a lookup table.
You type example.com
Browser checks its own DNS cache first. If found and not expired, done — no network trip needed.
OS cache & hosts file
OS checks its DNS cache, then /etc/hosts. Still nothing → asks the Recursive Resolver.
Recursive resolver
Your ISP's (or 8.8.8.8's) resolver does the hard work on your behalf. It checks its own cache first.
Root nameserver
"Who handles .com?" 13 root server clusters worldwide. Returns address of the .com TLD nameserver.
TLD nameserver
"Who handles example.com?" Returns the authoritative nameserver for that specific domain.
Authoritative nameserver
Returns the actual IP: 93.184.216.34. Resolver caches this result (TTL), sends it back to you.
Browser connects
TCP handshake → TLS → HTTP request. The whole DNS lookup took ~20ms and is now cached.
| Record | Purpose | Example |
|---|---|---|
| A | Hostname → IPv4 address | example.com → 93.184.216.34 |
| AAAA | Hostname → IPv6 address | example.com → 2606:2800:... |
| MX | Mail server for domain | @ → mail.example.com |
| CNAME | Alias for another hostname | www → example.com |
| TXT | Arbitrary text (SPF, DKIM, verification) | v=spf1 include:... |
| NS | Authoritative nameservers for domain | ns1.example.com |
HTTP & HTTPS
HTTP is the language browsers and servers use to exchange web content. HTTPS is HTTP with TLS encryption wrapped around it.
TCP delivers bytes reliably, but doesn't define what those bytes mean. HTTP defines the format and vocabulary: how to request a resource, how to describe the response, how to pass metadata. Without HTTP, every browser would need a custom agreement with every web server.
Host: example.com ← which server (virtual hosting)
Accept: text/html ← what formats I accept
Connection: keep-alive ← reuse TCP connection
── server responds ──
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1234
<html>...</html> ← the actual page body
| Range | Meaning | Common examples |
|---|---|---|
| 1xx | Informational | 100 Continue |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301 Moved Permanently, 302 Found |
| 4xx | Client error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | Server error | 500 Internal Server Error, 503 Unavailable |
HTTP/1.1
One request at a time per connection. Keep-alive added connection reuse. Still widely supported.
HTTP/2
Multiplexing — multiple requests over one TCP connection simultaneously. Binary protocol, header compression.
HTTP/3
Runs over QUIC (UDP-based). Eliminates TCP head-of-line blocking. Faster connection setup.
HTTPS / TLS
HTTP + TLS layer. Encrypts everything after the TCP handshake. TLS handshake happens before the first HTTP byte.
Email protocols
Email uses three protocols because sending and receiving are fundamentally different operations — each needs its own design.
Sending (SMTP) is a push operation to a server that may be temporarily unavailable. Retrieval (IMAP/POP3) is a pull operation that needs to manage folder state. IMAP and POP3 have entirely different philosophies: where mail lives and whether multiple devices should stay in sync.
SMTP (25 / 587)
Sending. Port 587 = authenticated submission (your client → your server). Port 25 = server-to-server relay. STARTTLS encrypts the connection.
IMAP (143 / 993)
Receiving. Mail stays on the server. Multiple devices see identical folder and read/unread state. Port 993 = IMAP over TLS. The modern standard.
POP3 (110 / 995)
Receiving. Downloads mail to your device and deletes from server. Offline-first, single-device model. Port 995 = POP3 over TLS.
SPF / DKIM / DMARC
Authentication. DNS-based records that prove mail genuinely came from the domain it claims. Stop spoofing and improve deliverability.
Your client → SMTP:587 → your mail server (MUA→MTA)
Your server → SMTP:25 → recipient's mail server (MTA→MTA)
stored in recipient mailbox
Recipient → IMAP:993 → downloads / syncs to client
DHCP
DHCP automatically assigns IP addresses, subnet masks, gateways, and DNS servers to devices when they join a network.
Before DHCP, every device required a manually configured IP, subnet mask, gateway, and DNS server. In a company with thousands of machines — or a café with daily visitors — that doesn't scale. DHCP makes joining a network a zero-configuration experience.
D — Discover
New device broadcasts to 255.255.255.255: "Is there a DHCP server? I need an IP." Has no IP yet, so must broadcast.
O — Offer
DHCP server responds with an offer: "You can have 192.168.1.42 for 24 hours." Multiple servers may reply.
R — Request
Device broadcasts: "I'd like the offer from server X." Broadcasting notifies all servers which offer was accepted.
A — Acknowledge
Server confirms: "192.168.1.42 is yours for 24 hours. Gateway: 192.168.1.1. DNS: 8.8.8.8." Done.
Routing & routers
Routers forward IP packets between networks. They read the destination IP, consult a routing table, and forward the packet one hop closer to its destination.
Switches connect devices on the same network. Routers connect different networks together — including your home network to the internet. Every time a packet crosses from one IP subnet to another, it passes through a router. The internet is, at its core, a massive mesh of routers sharing routing information.
Routing table
Every router has a table of known networks and the interface/next-hop to use. The most specific matching route wins — longest prefix match.
Default gateway
The catch-all route: 0.0.0.0/0. "If no specific route matches, send it here." Your home router is the default gateway for your devices.
Dynamic routing
Protocols like OSPF and BGP let routers share route information automatically and adapt to failures. BGP holds the internet together.
TTL countdown
Each router decrements IP TTL by 1. At 0, the packet is dropped and an ICMP Time Exceeded is sent back. Traceroute exploits this deliberately.
Routing table:
0.0.0.0/0 → WAN (default, least specific)
192.168.0.0/16 → LAN interface
192.168.1.0/24 → eth1 ← wins (most specific)
Longest prefix (most specific) match always wins.
Switching & VLANs
Switches connect devices on the same network at Layer 2 using MAC addresses. VLANs create logical network segments on the same physical hardware.
A hub broadcasts every frame to every port — everyone sees everything. A switch learns which MAC address lives on which port (MAC address table) and forwards frames only to the correct port. This dramatically reduces unnecessary traffic and gives you basic isolation between devices.
MAC address table
Switch learns by observing source MACs on each port. Known destinations → forwarded directly. Unknown destinations → flooded to all ports.
Flooding
Unknown MAC or broadcast frames are copied to every port except the incoming one. This is how ARP requests propagate across a LAN.
VLANs
Virtual LANs segment a physical switch into isolated logical networks. VLAN 10 and VLAN 20 can't communicate directly — even on the same switch. Routing is required to cross VLANs.
Trunk ports
Carries traffic for multiple VLANs between switches. Frames are tagged with an 802.1Q header indicating their VLAN membership.
NAT & PAT
Network Address Translation lets many private IP addresses share one public IP. Without it, IPv4 would have run out even sooner.
IPv4 has ~4 billion addresses. There are ~15 billion internet-connected devices. NAT bridges this gap: your home router presents one public IP to the internet while your 10 devices use private addresses internally. The router tracks which internal device made each request and maps responses back correctly.
Static NAT
Maps one private IP to one public IP, 1:1. Used for servers that need a consistent, predictable public address.
PAT (overload)
Many private IPs share one public IP, distinguished by port numbers. What your home router does. Also called NAT overload or masquerade.
NAT table
Router tracks: private IP:port ↔ public IP:port mappings. Inbound responses are matched and forwarded to the correct internal host.
Limitations
Breaks end-to-end connectivity — external hosts can't initiate connections to NATted devices. Port forwarding works around this. IPv6 eliminates the need entirely.
192.168.1.10:54321 → google.com:443
192.168.1.11:54322 → google.com:443
Both appear to Google as:
203.0.113.1:54321 → google.com:443
203.0.113.1:54322 → google.com:443
Router maps responses back to the right internal IP
Firewalls & network security
Firewalls filter traffic based on rules. Understanding them means understanding the layers they operate at and what they can and cannot see.
Every open port is a potential entry point. Firewalls enforce a policy: which traffic is allowed, from where, to where, on which ports. Without them, any internet device could attempt connections to your services. They're the primary tool for enforcing network boundaries.
Packet filter (L3/L4)
Inspects IP headers and TCP/UDP ports. Fast but simple — allows/blocks based on source IP, destination IP, and port number alone.
Stateful firewall
Tracks connection state. Knows a response packet belongs to an established connection. Blocks unsolicited inbound even if it looks like a valid response.
Application (L7) firewall
Inspects application-layer content — HTTP headers, DNS queries, TLS certs. Can block specific URLs, detect SQL injection, enforce policies.
IDS / IPS
Intrusion Detection/Prevention Systems watch for attack patterns. IDS alerts; IPS actively blocks. Uses signature matching and anomaly detection.
Protocol reference
Every major TCP/IP protocol — sorted by layer, with ports and transport.
| Protocol | Port(s) | Transport | Purpose |
|---|---|---|---|
| HTTP | 80 | TCP | Web pages (unencrypted) |
| HTTPS | 443 | TCP | Web pages (TLS encrypted) |
| DNS | 53 | UDP / TCP | Name resolution |
| SMTP | 25, 587 | TCP | Send email |
| IMAP | 143, 993 | TCP | Retrieve email (server-side sync) |
| POP3 | 110, 995 | TCP | Retrieve email (download & delete) |
| SSH | 22 | TCP | Encrypted remote shell access |
| FTP | 20, 21 | TCP | File transfer (unencrypted) |
| SFTP | 22 | TCP | Encrypted file transfer (via SSH) |
| DHCP | 67, 68 | UDP | Automatic IP address assignment |
| NTP | 123 | UDP | Network time synchronisation |
| SNMP | 161, 162 | UDP | Network device monitoring & management |
| RDP | 3389 | TCP | Remote desktop (Windows) |
| LDAP | 389, 636 | TCP | Directory services (Active Directory) |
| Protocol | Layer | Purpose |
|---|---|---|
| TCP | Transport (4) | Reliable, ordered, connection-oriented delivery |
| UDP | Transport (4) | Fast, connectionless, best-effort delivery |
| IP | Network (3) | Logical addressing and routing across networks |
| ICMP | Network (3) | Error messages and diagnostics (ping, traceroute) |
| ARP | Link / Network | Resolve IP address → MAC address on a LAN |
| OSPF | Network (3) | Dynamic interior routing (within an org) |
| BGP | Application / Network | Internet inter-domain routing — the backbone protocol |
| IPSec | Network (3) | Encryption and authentication at the IP layer (VPNs) |
Final quiz
12 questions across all five modules. Each one tests the purpose behind the concept, not just the name.