Mastering TCP: Handshakes, Packet Structure, and Real‑World Wireshark Analysis
This article provides a comprehensive guide to TCP, covering its definition, connection-oriented nature, reliability, byte‑stream model, detailed packet header fields, three‑way handshake, four‑way termination, MTU/MSS concepts, Python simulation scripts, Wireshark capture techniques, common pitfalls, and practical networking programming steps.
1. What is TCP?
TCP (Transmission Control Protocol) is a connection‑oriented, reliable, byte‑stream transport‑layer protocol defined by IETF RFC 793.
What does "connection‑oriented" mean?
Unlike UDP, TCP establishes a connection with a three‑way handshake before data transfer.
What does "reliable" mean?
TCP uses handshakes, retransmission, and timeout mechanisms to ensure data reaches the destination despite network issues.
What does "byte‑stream" mean?
TCP treats data as an unstructured stream of bytes, allowing variable‑size segments and buffering.
2. Complete TCP Header Format
The TCP segment header consists of several fields:
Source Port (2 bytes) and Destination Port (2 bytes)
Sequence Number (4 bytes)
Acknowledgment Number (4 bytes)
Data Offset (4 bits)
Window Size (16 bits)
Reserved (6 bits)
Urgent Pointer (16 bits)
Flags : SYN, ACK, RST, FIN, PSH, URG
Options are variable‑length (up to 40 bytes) and include MSS, window scaling, and timestamps.
3. Simulating a TCP Connection
Two simple Python scripts demonstrate a TCP server and client.
# tcp_server.py
import socket
import time
s = socket.socket()
host = socket.gethostname()
port = 13200
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
c.send('hello'.encode('utf-8'))
c.send('world'.encode('utf-8'))
time.sleep(1)
c.close()Run the server and verify the listening port with lsof -i:13200.
# tcp_client.py
import socket
import time
s = socket.socket()
host = socket.gethostname()
port = 13200
s.connect((host, port))
print(s.recv(1024))
time.sleep(2)
s.close()4. Wireshark Capture Walkthrough
Capture traffic on port=13200 and analyze the three‑way handshake, data transfer (PSH packets), and four‑way termination.
Three‑Way Handshake
1️⃣ SYN (seq = 0) → Server 2️⃣ SYN+ACK (seq = x, ack = 1) ← Server 3️⃣ ACK (ack = x+1) → Server
Data Transfer
The server sends two PSH packets containing hello and world. Sequence numbers increase accordingly.
Four‑Way Termination
1️⃣ FIN (seq = 11) → Server 2️⃣ ACK (ack = 12) ← Client 3️⃣ FIN (seq = 12) → Client 4️⃣ ACK (ack = 13) ← Server
5. Four Thought‑Provoking Questions
Why three‑way handshake?
Ensures both sides can send and receive, synchronizes initial sequence numbers, and prevents old duplicate connections.
Why not two‑way?
Two‑way cannot guarantee bidirectional communication and may create redundant connections when packets are retransmitted.
Why not four‑way?
Four‑way would split the SYN+ACK exchange into two steps, adding unnecessary latency.
Why not more than five?
Extra handshakes add overhead without improving reliability.
6. MTU and MSS
MTU
Maximum Transmission Unit – the largest IP packet that can traverse a physical network (e.g., 1500 bytes for Ethernet).
MSS
Maximum Segment Size – the largest amount of TCP payload data that can fit in a segment: MSS = MTU – IP‑header – TCP‑header.
7. Typical Network Programming Steps
Server :
Create a socket with socket() (Optional) Set socket options with setsockopt() Bind address and port with bind() Listen for connections with listen() Accept a client with accept() Send/receive data with send() and recv() Close the connection and the listening socket
Client :
Create a socket
(Optional) Set socket options
(Optional) Bind a local address
Connect to the server with connect() Send/receive data
Close the connection
Key Functions
connect() – blocks until the three‑way handshake succeeds. listen() – marks a socket as passive and sets the backlog queue. accept() – blocks until an established connection is available.
8. Important Notes
ack vs. ACK
Upper‑case ACK is a flag in the TCP header; lower‑case ack is the acknowledgment number (next expected byte).
Maximum TCP payload
On Ethernet, the practical MSS is 1460 bytes (1500 MTU − 20 IP − 20 TCP).
9. Abnormal Scenarios
Connecting to a non‑listening port
The client receives a RST packet and raises ConnectionRefusedError.
Traceback (most recent call last):
File "tcp_client.py", line 8, in <module>
s.connect((host, port))
ConnectionRefusedError: [Errno 61] Connection refusedConnecting to a down host
The client repeatedly sends SYN packets without receiving a response.
Server application blocked
Even if the server process is hung, the three‑way handshake can complete because the kernel handles it; data may be buffered until the application calls accept().
10. References
Nearly 40 illustrated TCP handshake and termination interview questions
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
