Skip to content

Network Protocols

TCP (Transmission Control Protocol)

TCP provides reliable, ordered, connection-oriented communication.

The TCP packet

packet
0-15: "Source Port"
16-31: "Destination Port"
32-63: "Sequence Number"
64-95: "Acknowledgment Number"
96-99: "Data Offset"
100-105: "Reserved"
106: "URG"
107: "ACK"
108: "PSH"
109: "RST"
110: "SYN"
111: "FIN"
112-127: "Window"
128-143: "Checksum"
144-159: "Urgent Pointer"
160-191: "(Options and Padding)"
192-255: "Data (variable length)"

Three-Way Handshake

sequenceDiagram
    Client->>Server: SYN (seq=x)
    Server->>Client: SYN-ACK (seq=y, ack=x+1)
    Client->>Server: ACK (seq=x+1, ack=y+1)
    Note over Client,Server: Connection ESTABLISHED

Steps:

  1. Client → Server: SYN with initial sequence number
  2. Server → Client: SYN-ACK acknowledges and sends own sequence number
  3. Client → Server: ACK completes handshake

Why three-way?

  • Prevents old duplicate connections
  • Synchronizes sequence numbers
  • Establishes bidirectional communication
# Observe with tcpdump
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0'

Four-Way Termination

sequenceDiagram
    Client->>Server: FIN (seq=x)
    Server->>Client: ACK (ack=x+1)
    Server->>Client: FIN (seq=y)
    Client->>Server: ACK (ack=y+1)
    Note over Client: TIME_WAIT (2*MSL)

Why four-way?

  • TCP is full-duplex
  • Each direction must be closed independently

TIME_WAIT state:

  • Lasts 2 * MSL (Maximum Segment Lifetime, typically 60-120s)
  • Ensures old packets expire
  • Allows final ACK to be retransmitted
# View TIME_WAIT connections
netstat -an | grep TIME_WAIT
ss -tan | grep TIME-WAIT

TCP Flags

Flag Meaning Use
SYN Synchronize Connection establishment
ACK Acknowledgment Acknowledging data
FIN Finish Connection termination
RST Reset Abort connection
PSH Push Send data immediately
URG Urgent Urgent data

Flow Control (Sliding Window)

TCP uses a sliding window for flow control.

Sender Window:
[Sent & ACKed][Sent not ACKed][Can send][Can't send yet]

Receiver Window:
[Received & ACKed][Can receive][Can't receive yet]

Window Size: Advertised by receiver

# View TCP window
tcpdump -i eth0 -nn -vv 'tcp'
# Look for "win" field

Congestion Control

TCP adjusts transmission rate based on network conditions.

Algorithms:

  1. Slow Start: Exponential growth
  2. Start with small window (typically 1-10 segments)
  3. Double window each RTT
  4. Until threshold or packet loss

  5. Congestion Avoidance: Linear growth

  6. Increase window by 1 per RTT
  7. After reaching threshold

  8. Fast Retransmit: On 3 duplicate ACKs

  9. Retransmit without waiting for timeout

  10. Fast Recovery: After fast retransmit

  11. Reduce window but don't start from 1
# View congestion control algorithm
sysctl net.ipv4.tcp_congestion_control
# Common: cubic, reno, bbr

# Change algorithm
sysctl -w net.ipv4.tcp_congestion_control=bbr

TCP States

LISTEN → SYN_SENT → ESTABLISHED → FIN_WAIT_1 → FIN_WAIT_2 → TIME_WAIT → CLOSED
        SYN_RECEIVED → ESTABLISHED → CLOSE_WAIT → LAST_ACK → CLOSED
# View TCP state counts
ss -tan | awk '{print $1}' | sort | uniq -c

UDP (User Datagram Protocol)

UDP provides connectionless, unreliable communication.

Characteristics

  • No connection setup: No handshake
  • No reliability: No ACKs, no retransmission
  • No ordering: Packets may arrive out of order
  • No flow/congestion control
  • Low overhead: 8-byte header vs TCP's 20+

UDP Datagram

packet
0-15: "Source Port"
16-31: "Destination Port"
32-47: "Length"
48-63: "Checksum"
64-127: "Data (variable length)"

Use Cases

  • DNS: Fast lookups
  • DHCP: Bootstrap
  • Streaming: Video, audio (some loss acceptable)
  • Gaming: Low latency required
  • VPN: Some VPNs use UDP

TCP vs UDP

Feature TCP UDP
Connection Connection-oriented Connectionless
Reliability Reliable Unreliable
Ordering Ordered Unordered
Speed Slower Faster
Overhead Higher Lower
Use case Data integrity matters Speed/latency matters

DNS (Domain Name System)

DNS translates domain names to IP addresses.

DNS Resolution Process

Recursive query from client perspective:

sequenceDiagram
    participant User as 👤 User/Browser
    participant Cache as 💾 OS<br/>(local cache)
    participant Resolver as 🔍 Recursive Resolver<br/>(ISP or 8.8.8.8)
    participant Root as 🌐 Root Server<br/>(. - 13 root servers)
    participant TLD as 🏢 TLD Server<br/>(.com registry)
    participant Auth as ✅ Authoritative NS<br/>(google.com)

    Note over User,Auth: DNS Resolution for www.google.com

    User->>Cache: 1. Check local cache
    alt Cache Hit
        Cache-->>User: Return cached IP
    end

    Cache->>Resolver: 2. Recursive query:<br/>www.google.com?

    Note over Resolver: Check resolver cache

    alt Not in Resolver Cache
        Resolver->>Root: 3. Iterative query:<br/>www.google.com?
        Root-->>Resolver: 4. Referral:<br/>Ask .com TLD server<br/>(IP: 192.5.6.30)

        Resolver->>TLD: 5. Iterative query:<br/>www.google.com?
        TLD-->>Resolver: 6. Referral:<br/>Ask google.com NS<br/>(ns1.google.com)

        Resolver->>Auth: 7. Iterative query:<br/>www.google.com?
        Auth-->>Resolver: 8. Authoritative answer:<br/>A record: 142.250.185.46<br/>TTL: 300 seconds
    end

    Resolver-->>Cache: 9. Response + cache<br/>142.250.185.46
    Cache-->>User: 10. Return IP:<br/>142.250.185.46

    Note over User: www.google.com is at 142.250.185.46
# DNS lookup
dig www.google.com
nslookup www.google.com
host www.google.com

# Trace full resolution
dig +trace www.google.com

# Query specific server
dig @8.8.8.8 www.google.com

# Reverse DNS
dig -x 8.8.8.8

DNS Record Types

Type Purpose Example
A IPv4 address 192.0.2.1
AAAA IPv6 address 2001:db8::1
CNAME Alias www → webserver
MX Mail server mail.example.com
NS Name server ns1.example.com
TXT Text data SPF, DKIM
PTR Reverse lookup 1.2.0.192.in-addr.arpa
SOA Zone authority Primary name server

Recursive vs Iterative Queries

Recursive: Server does all the work

Client → Resolver: "What is www.google.com?"
Resolver → Client: "Here's the IP"

Iterative: Server provides referrals

Client → Server: "What is www.google.com?"
Server → Client: "Ask this TLD server"
Client → TLD: "What is www.google.com?"
TLD → Client: "Ask this authoritative server"

DHCP (Dynamic Host Configuration Protocol)

DHCP automatically assigns IP configurations.

DORA Process

sequenceDiagram
    Client->>Broadcast: DHCPDISCOVER
    Server->>Broadcast: DHCPOFFER
    Client->>Broadcast: DHCPREQUEST
    Server->>Broadcast: DHCPACK

Steps:

  1. Discover: Client broadcasts "I need an IP"
  2. Offer: Server offers IP address
  3. Request: Client requests offered IP
  4. Acknowledge: Server confirms

Information provided:

  • IP address
  • Subnet mask
  • Default gateway
  • DNS servers
  • Lease time
# Request new lease
dhclient -r eth0  # Release
dhclient eth0     # Request

# View lease
cat /var/lib/dhcp/dhclient.leases

ARP (Address Resolution Protocol)

ARP resolves IP addresses to MAC addresses.

ARP Process

Who has 192.168.1.1? Tell 192.168.1.10
→ Broadcast to FF:FF:FF:FF:FF:FF

192.168.1.1 is at 00:11:22:33:44:55
→ Unicast reply
# View ARP cache
arp -a
ip neigh show

# Clear ARP cache
ip neigh flush all

# Send ARP request
arping -I eth0 192.168.1.1

RARP and Gratuitous ARP

RARP: Reverse ARP (MAC → IP, obsolete)

Gratuitous ARP: Announce own IP

  • Detect IP conflicts
  • Update ARP caches
  • Used in failover

ICMP (Internet Control Message Protocol)

ICMP is used for diagnostics and error reporting.

Common ICMP Messages

Type Code Message Use
0 0 Echo Reply Ping response
3 0-15 Destination Unreachable Various reasons
5 0-3 Redirect Route optimization
8 0 Echo Request Ping
11 0 Time Exceeded TTL=0 (traceroute)
# Ping (ICMP Echo)
ping -c 4 8.8.8.8

# Traceroute (ICMP Time Exceeded)
traceroute google.com
mtr google.com  # Better traceroute

# Path MTU discovery
ping -M do -s 1472 google.com

HTTP/HTTPS

HTTP Request

GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
Connection: keep-alive

HTTPS/TLS Handshake

sequenceDiagram
    participant Client as 👤 Client<br/>(Browser)
    participant Server as 🖥️ Server<br/>(www.example.com)

    Note over Client,Server: TLS 1.3 Handshake

    Note over Client,Server: Flight 1: Client Hello
    Client->>Server: 1. ClientHello<br/>• TLS version (1.3)<br/>• Random (32 bytes)<br/>• Cipher suites list<br/>• Supported groups (curves)<br/>• Key share (public key)<br/>• Extensions (SNI, ALPN)

    Note over Client,Server: Flight 2: Server Response
    Server->>Client: 2. ServerHello<br/>• TLS version (1.3)<br/>• Random (32 bytes)<br/>• Selected cipher suite<br/>• Key share (public key)
    Note over Client,Server: 🔐 Both sides compute shared secret (ECDHE)
    Server->>Client: 3. EncryptedExtensions<br/>• Additional extensions<br/>🔒 Encrypted from here
    Server->>Client: 4. Certificate<br/>• Server's X.509 certificate<br/>• Certificate chain<br/>🔒 Encrypted
    Server->>Client: 5. CertificateVerify<br/>• Digital signature<br/>• Proves private key ownership<br/>🔒 Encrypted
    Server->>Client: 6. Finished<br/>• MAC of all handshake messages<br/>• Confirms integrity<br/>🔒 Encrypted

    Note over Client,Server: Flight 3: Client Confirmation
    Note over Client: ✅ Verify certificate<br/>✅ Check signature<br/>✅ Validate chain

    Client->>Server: 7. Finished<br/>• MAC of all handshake messages<br/>🔒 Encrypted

    Note over Client,Server: 🎉 Handshake Complete - Application Data
    Client->>Server: 8. Application Data<br/>(HTTP request)<br/>🔒 Encrypted
    Server->>Client: 9. Application Data<br/>(HTTP response)<br/>🔒 Encrypted

Practice Questions

  1. Explain TCP three-way handshake in detail.
  2. Why is TIME_WAIT state necessary?
  3. What is the difference between TCP and UDP?
  4. Explain the complete DNS resolution process.
  5. What is the DHCP DORA process?
  6. How does ARP work?
  7. What happens during a TLS handshake?
  8. Why does TCP use both flow control and congestion control?

Further Reading

  • RFC 793 - TCP
  • RFC 768 - UDP
  • RFC 1035 - DNS
  • RFC 2131 - DHCP
  • RFC 826 - ARP