MODULE 02 — NETWORKING

Packets & TCP

Dissect how data is packaged and delivered across networks — TCP headers, flags, the famous 3-way handshake, and how UDP trades reliability for speed.

What Are Packets?

When you send data over a network — whether it's a webpage, an email, or a video call — the data doesn't travel as one giant block. Instead, it gets broken down into small, manageable chunks called packets. Each packet contains a piece of the data plus header information (source address, destination address, sequence number, etc.) that tells the network how to deliver and reassemble it.

Think of it like sending a book through the mail. Rather than shipping the entire book in one box, you tear out each chapter, put it in a separate envelope with a number on it, and mail them all independently. The recipient collects all the envelopes and reassembles the book using the chapter numbers. That's essentially what packet switching does.

The two primary Transport Layer protocols responsible for packaging and delivering data are TCP and UDP. Understanding when and why each is used is fundamental to networking and cybersecurity.

Key Terms

Packet: A unit of data formatted for transmission across a network, containing both payload (actual data) and headers (routing info).
Segment: The term used for data at the Transport Layer (Layer 4). TCP uses segments; UDP uses datagrams.
Port: A number (0–65535) that identifies a specific process or service on a machine. HTTP uses port 80, HTTPS uses 443.
Socket: The combination of an IP address and a port number (e.g., 192.168.1.10:443) that uniquely identifies a connection endpoint.
Handshake: A process where two systems agree on connection parameters before exchanging data.
Latency: The time it takes for a packet to travel from source to destination, measured in milliseconds (ms).

TCP — Transmission Control Protocol

TCP is the workhorse of the internet. It's a connection-oriented protocol, meaning that before any data is exchanged, TCP first establishes a dedicated connection between the sender and receiver through a process called the 3-way handshake. This ensures both sides are ready to communicate.

  • Connection-oriented: Establishes a connection before sending data using the 3-way handshake (SYN → SYN-ACK → ACK). This setup phase adds latency but ensures reliability.
  • Reliable Delivery: Every segment sent is acknowledged (ACK). If the sender doesn't receive an acknowledgment within a timeout period, it retransmits the segment. This guarantees that all data arrives, even if parts of the network are congested or lossy.
  • Ordered Delivery: Each segment is assigned a sequence number. The receiver uses these numbers to reassemble data in the correct order, regardless of the order packets actually arrive at the destination.
  • Flow Control (Sliding Window): TCP uses a window size mechanism where the receiver tells the sender how much buffer space is available. The sender adjusts its transmission rate to prevent overwhelming the receiver. This is dynamic — the window grows and shrinks based on conditions.
  • Congestion Control: TCP monitors network congestion using algorithms like Slow Start, Congestion Avoidance, and Fast Retransmit. If packet loss is detected, TCP reduces its sending rate to avoid making congestion worse.
  • Error Detection: TCP includes a checksum in every segment header. The receiver recalculates the checksum; if it doesn't match, the segment is discarded and retransmitted.
  • Use Cases: HTTP/HTTPS (web), SSH (remote access), FTP (file transfer), SMTP/IMAP (email), database connections — anything that requires guaranteed, ordered delivery.

UDP — User Datagram Protocol

UDP is TCP's lean, fast sibling. It's connectionless — there is no handshake, no connection setup, no acknowledgments. The sender simply packages data into a datagram and sends it. Whether it arrives or not is not UDP's concern. This "fire and forget" approach makes it incredibly fast.

  • Connectionless: No handshake is required. The sender simply starts sending datagrams to the destination IP and port. This eliminates the setup latency that TCP incurs.
  • No Reliability Guarantees: There are no acknowledgments, no retransmissions, and no sequence numbers. If a packet is lost in transit, it's simply gone. The application must handle loss detection if needed.
  • Minimal Overhead: UDP headers are only 8 bytes (vs. TCP's minimum of 20 bytes). With no connection state tracking, no window management, and no retransmission logic, UDP is lightweight and fast.
  • No Ordering: Datagrams may arrive out of order. For applications like video streaming, this is acceptable — a slightly out-of-order frame is better than a delayed one.
  • Broadcast & Multicast: UDP supports sending to multiple destinations simultaneously, making it ideal for network discovery protocols (DHCP, mDNS) and live streaming.
  • Use Cases: DNS lookups (fast, small queries), VoIP/video calls (real-time, loss-tolerant), online gaming (speed matters more than perfection), DHCP, SNMP, and streaming media.

TCP vs. UDP — Head-to-Head

Feature TCP UDP
Connection Connection-oriented (handshake) Connectionless (no setup)
Reliability Guaranteed delivery (ACKs) Best-effort, no guarantees
Ordering Sequence numbers ensure order No ordering
Speed Slower (overhead) Faster (minimal overhead)
Header Size 20–60 bytes 8 bytes
Flow Control Yes (sliding window) No
Error Handling Checksum + retransmission Checksum only (optional)
Use Cases Web, email, file transfer DNS, VoIP, gaming, streaming

The 3-Way Handshake (Connection Setup)

Before TCP can send any data, both sides must agree to communicate. This process — the 3-way handshake — establishes a connection and synchronizes sequence numbers. It happens every time you open a website, send an email, or SSH into a server.

1
SYN

The client sends a SYN (Synchronize) segment with its Initial Sequence Number (ISN). This is like saying: "Hey server, I want to talk. My starting sequence number is X."

2
SYN-ACK

The server acknowledges the client's SYN (ACK = X+1) and sends its own SYN with its own ISN. "Got your number. Here's mine — my starting sequence is Y."

3
ACK

The client acknowledges the server's SYN (ACK = Y+1). The connection is now ESTABLISHED and data transfer begins. The whole process typically takes <1ms on a LAN.

The 4-Way Teardown (Connection Termination)

Closing a TCP connection is a 4-step process because the connection is full-duplex — each direction must be closed independently. Either side can initiate the close.

1
FIN

The initiator sends a FIN segment: "I'm done sending data."

2
ACK

The other side acknowledges: "Got it, I'll finish my remaining data."

3
FIN

The other side sends its own FIN: "I'm also done now."

4
ACK

Final acknowledgment. Connection fully closed. Both sides free their resources.

Note: If a connection needs to be terminated abruptly (crash, error), a RST (Reset) flag is sent instead — this immediately destroys the connection with no negotiation.

Real-World Example: What Happens When You Visit a Website?

  1. Your browser resolves www.example.com to an IP address via DNS (using UDP port 53).
  2. Your browser initiates a TCP 3-way handshake with the server on port 443 (HTTPS).
  3. Once connected, a TLS handshake occurs inside the TCP connection (encryption setup).
  4. Your browser sends an HTTP GET request as TCP segments. The server responds with the HTML page, also in TCP segments.
  5. Your browser renders the page. When done, the connection is closed with a 4-way teardown (or kept alive for more requests).

All of this happens in under a second — TCP handles the reliability, ordering, and flow control transparently.

TCP Header Structure (20 bytes minimum)

Every TCP segment begins with a header that contains all the metadata needed for reliable delivery. Understanding this header is essential for packet analysis with tools like Wireshark. Let's break down each field:

Source Port
16 bits
Destination Port
16 bits
Sequence Number
32 bits
Acknowledgment Number
32 bits
Offset
4b
Reserved
3b
Flags
9 bits
Window
16b
Checksum
16 bits
Urgent Pointer
16 bits
  • Source/Dest Port (16 bits each): Identifies the sending and receiving application. Common ports: 80 (HTTP), 443 (HTTPS), 22 (SSH), 25 (SMTP).
  • Sequence Number (32 bits): Tracks the byte position in the data stream. During the handshake, this carries the Initial Sequence Number (ISN), a randomly generated value to prevent spoofing attacks.
  • Acknowledgment Number (32 bits): The next sequence number the receiver expects. If the sender sent bytes 1–100, the ACK number will be 101.
  • Data Offset (4 bits): Tells the receiver where the actual data begins (header length in 32-bit words). Minimum value is 5 (20 bytes).
  • Flags (9 bits): Control bits (SYN, ACK, FIN, RST, PSH, URG, etc.) that dictate the segment's purpose. See the flags section below.
  • Window Size (16 bits): How many bytes the receiver can accept. This is the key to TCP's flow control mechanism. A window of 0 means "stop sending — I'm full."
  • Checksum (16 bits): Covers the header + data + a pseudo-header (source/dest IP). Used to detect corruption in transit.

TCP Flags — The Control Bits

TCP flags are single-bit fields in the header that control the state of the connection. In Wireshark, you'll see these in every TCP packet. Knowing what each flag means is critical for understanding network traffic and detecting anomalies.

SYN
Synchronize. Initiates a new connection. Carries the Initial Sequence Number. Seen in the first packet of every TCP handshake.
ACK
Acknowledge. Confirms receipt of data. Present in almost every TCP segment after the initial SYN (including SYN-ACK).
FIN
Finish. Signals the sender is done transmitting. Used in graceful connection termination (4-way teardown).
RST
Reset. Immediately aborts the connection. Sent when something is wrong — port closed, connection doesn't exist, or error detected.
PSH
Push. Tells the receiver to deliver data to the application immediately rather than buffering. Used in interactive sessions like SSH.
URG
Urgent. Indicates high-priority data that should be processed before other data in the buffer. Rarely used in modern protocols.
Security Note: Unusual flag combinations (like SYN+FIN, all flags set "XMAS scan", or no flags "NULL scan") are hallmarks of port scanning techniques used by tools like Nmap. IDS/IPS systems flag these as suspicious.

Windowing & Flow Control

TCP's sliding window is one of its most elegant features. It controls how much data can be "in flight" (sent but not yet acknowledged) at any time, balancing speed and reliability.

How It Works

  1. The receiver advertises a window size in every ACK it sends (e.g., "I can accept 65,535 bytes").
  2. The sender can transmit up to that many bytes without waiting for acknowledgment.
  3. As ACKs arrive, the window "slides" forward, allowing more data to be sent.
  4. If the receiver's buffer fills up, it advertises window size 0, and the sender pauses.

Congestion Control Algorithms

  • Slow Start: Connection begins with a small congestion window (cwnd), doubling it each round-trip until loss occurs.
  • Congestion Avoidance: After threshold, growth becomes linear (additive increase) to probe for available bandwidth carefully.
  • Fast Retransmit: If 3 duplicate ACKs are received, retransmit the missing segment immediately (don't wait for timeout).
  • Fast Recovery: After fast retransmit, reduce cwnd by half instead of resetting to 1 — recovers faster.

UDP Header Structure (8 bytes)

UDP's header is deliberately simple — just 4 fields, 8 bytes total. Compare this to TCP's minimum 20-byte header. The simplicity is what makes UDP fast.

Source Port
16 bits
Destination Port
16 bits
Length
16 bits
Checksum
16 bits (optional in IPv4)

That's it. No sequence numbers. No acknowledgments. No window size. No flags. Just source, destination, length, and an optional integrity check.

Analyzing Packets with Wireshark

Wireshark is the industry-standard packet analyzer. It captures live network traffic and lets you inspect every byte of every packet. Here's how to use it for TCP/UDP analysis:

Filter: tcp.port == 443 — Show only HTTPS traffic
Filter: tcp.flags.syn == 1 && tcp.flags.ack == 0 — Show only initial SYN packets (new connections)
Filter: tcp.flags.rst == 1 — Show connection resets (potential scanning/errors)
Filter: udp.port == 53 — Show DNS queries and responses
Filter: tcp.analysis.retransmission — Show retransmitted segments (network issues)

In Wireshark, you can right-click any TCP stream and select "Follow TCP Stream" to reconstruct the entire conversation between client and server — incredibly useful for forensics and debugging.

Security: TCP/UDP Attack Vectors

SYN Flood Attack

The attacker sends thousands of SYN packets with spoofed source IPs. The server responds with SYN-ACKs to non-existent hosts and waits for ACKs that never come. Each half-open connection consumes server memory. Eventually, the server's connection table fills up and it can't accept legitimate connections.

Defense: SYN cookies (stateless SYN handling), connection timeouts, rate limiting, cloud DDoS mitigation (Cloudflare, AWS Shield).

TCP Session Hijacking

An attacker on the same network sniffs the sequence numbers of an active TCP session and injects packets with valid sequence numbers, effectively taking over the conversation. They can execute commands as the legitimate user.

Defense: Encryption (TLS/SSL), randomized ISNs, network segmentation.

UDP Amplification DDoS

The attacker sends small UDP requests (e.g., DNS queries) with the victim's IP as the source address. The servers respond with much larger replies to the victim. A 60-byte query can generate a 4,000-byte response — a 70x amplification factor.

Defense: BCP38 (ingress filtering), response rate limiting, disable open resolvers.

Port Scanning (Nmap)

Tools like Nmap use crafted TCP/UDP packets to discover open ports. A SYN scan sends SYN to each port — if SYN-ACK returns, the port is open. An XMAS scan sets FIN+PSH+URG flags to evade basic firewalls. A NULL scan sends no flags at all.

Defense: Firewalls, IDS/IPS, port knocking, limiting exposed services.

Common Port Numbers to Know

Port Protocol Service Notes
20/21 TCP FTP File Transfer (20=data, 21=control)
22 TCP SSH Secure Shell / encrypted remote access
23 TCP Telnet Unencrypted remote access (avoid!)
25 TCP SMTP Send email
53 TCP/UDP DNS Domain Name System
80 TCP HTTP Unencrypted web traffic
443 TCP HTTPS Encrypted web traffic (TLS)
3389 TCP RDP Windows Remote Desktop
8080 TCP HTTP Alt Common for proxies / dev servers

Well-known ports: 0–1023 (require root/admin). Registered: 1024–49151. Ephemeral/Dynamic: 49152–65535 (used by clients for outgoing connections).

3-Way Handshake Simulator

Watch TCP packets fly between Client and Server. Click "Start Handshake" to begin!

Client
192.168.1.10:49152
Server
93.184.216.34:443

TCP Flag Playground

Toggle TCP flags to build your own segment. The hex value and meaning update in real-time.

Flags value: 0x000 Meaning: No flags set

Knowledge Check

All certification names are referenced for educational purposes only. This project is not affiliated with any certification body.