TCP (Transmission Control Protocol) is a "Connection-Oriented" protocol. This means it requires a reliable session to be established before any data (like an HTML file) is sent. This contrasts with UDP, which just throws packets at the wall. The mechanism to establish this session is the famous 3-Way Handshake.
The Process (The Hello)
1. SYN (Synchronize): Client -> Server
"Hi, I want to talk to you on port 443. My Sequence Number is 1000."
2. SYN-ACK (Synchronize-Acknowledge): Server -> Client
"I hear you (ACK 1001). I also want to talk to you. My Sequence Number is 5000."
3. ACK (Acknowledge): Client -> Server
"I hear you too (ACK 5001). Connection Established. Let's send data."
1. Why the Sequence Numbers (ISN)?
Why not just start at 1?
Security. If attackers can guess the Sequence Number of an active connection, they can hijack it (TCP Hijacking) and inject malicious packets that look legitimate.
Modern Operating Systems generate ISN (Initial Sequence Numbers) randomly to prevent prediction.
2. TCP Flags (The Control Bits)
The TCP Header contains 6-9 control bits (flags). You see these in Wireshark:
| Flag | Name | Meaning |
|---|---|---|
| SYN | Synchronize | "Let's start a connection." Only set in the first packet. |
| ACK | Acknowledge | "I received packet X, please send X+1." Set in almost all packets. |
| RST | Reset | "Something is wrong. Kill the connection immediately." (Used by Firewalls to block ports). |
| FIN | Finish | "I have no more data to send. Let's close politely." |
3. SYN Flood Attack (DDoS)
The server must allocate memory (RAM) for every SYN packet it receives, waiting for the final ACK.
Attackers exploit this by sending millions of fake SYN packets (from spoofed IPs) and never sending the final ACK.
The server's memory fills up with "Half-Open Connections", preventing legitimate users from connecting.
Solution: SYN Cookies. The server doesn't allocate RAM. Instead, it encodes the session data into the Sequence Number itself. If the ACK comes back with the correct math, it knows the connection is valid.
4. The 4-Way Teardown (Goodbye)
Closing a connection takes 4 steps (or a modified 3-way):
1. Client: FIN
2. Server: ACK
... Server finishes sending remaining data ...
3. Server: FIN
4. Client: ACK
During this time, the port stays in a TIME_WAIT state for 2 MSL (Maximum Segment Lifetime), typically 60 seconds, to ensure no stray packets arrive late.