Typorithm · medium

TCP Handshake & Teardown

tcp-handshakenetworkstcphandshakesyn
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn TCP Handshake & Teardown

0%

L4 — Transport Layer

TCP is connection-oriented, reliable, and ordered. A connection opens with the 3-way handshake (SYN, SYN-ACK, ACK) to synchronize sequence numbers, and closes with the FIN/ACK exchange. Sockets move through states like LISTEN, ESTABLISHED, and TIME_WAIT, which ss -tan reveals.

TCP is connection-oriented: before any data flows, both ends complete a 3-way handshake. The client sends SYN, the server replies SYN-ACK, and the client answers ACK. This exchange synchronizes the initial sequence numbers each side will use to make the stream reliable and ordered.

Closing is the mirror image: each side sends a FIN that the other ACKs, so a full teardown is FIN, ACK, FIN, ACK. Because each direction closes independently, you may briefly see a half-closed connection.

A socket transitions through well-defined states — LISTEN while waiting, ESTABLISHED once the handshake completes, and TIME_WAIT after closing to absorb late packets. ss -tan lists every TCP socket and the state it is in.

01

Open: SYN -> SYN-ACK -> ACK synchronizes sequence numbers.

02

Close: FIN -> ACK -> FIN -> ACK, each side independently.

03

ss -tan lists TCP sockets and their state.

# 3-way: SYN -> SYN-ACK -> ACK
ss -tan
nc -v example.com 443
tcpdump -i any tcp port 443
# teardown: FIN -> ACK -> FIN -> ACK

Read the implementation

Connect each part of the code to the concept before you type.

1. The handshake

Opening a TCP connection takes three packets: SYN, SYN-ACK, then ACK.

# 3-way: SYN -> SYN-ACK -> ACK

2. List TCP sockets

ss -tan lists TCP sockets (-t) with numeric addresses (-n) and all states (-a), including their connection state.

ss -tan

3. Open a connection

nc -v opens a TCP connection and prints whether the handshake succeeded — a quick reachability test.

nc -v example.com 443

4. Capture packets

tcpdump captures TCP packets on port 443 so you can watch the SYN/ACK/FIN flags on the wire.

tcpdump -i any tcp port 443

5. Closing down

Each side closes independently with a FIN that the peer ACKs — the four-way teardown.

# teardown: FIN -> ACK -> FIN -> ACK

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

TCP Handshake & Teardown: Lesson & Practice · Typorithm | ApplyDjinn