Fundamentals 43 min read

Comprehensive Guide to TCP: Header Structure, Handshakes, Connection Management, and Socket Programming

This article provides an in‑depth tutorial on TCP, covering its header structure, three‑way handshake, reasons for three handshakes, four‑way termination, TIME_WAIT, SYN attacks, Linux kernel parameters, and practical socket programming examples, all illustrated with diagrams and code snippets.

IT Services Circle
IT Services Circle
IT Services Circle
Comprehensive Guide to TCP: Header Structure, Handshakes, Connection Management, and Socket Programming

This article begins with an overview of the TCP header, highlighting key fields such as the sequence number, acknowledgment number, and control flags (ACK, RST, SYN, FIN) and explains how they ensure reliable, ordered delivery of data.

It then details the three‑way handshake process (SYN, SYN‑ACK, ACK), explaining why three exchanges are required to prevent old duplicate connections, synchronize initial sequence numbers, and avoid resource waste.

The text also discusses the four‑way termination sequence, describing each FIN and ACK exchange, the TIME_WAIT state, and the rationale for waiting 2 MSL to ensure all delayed packets are discarded.

Common failure scenarios are examined, such as lost handshake packets and how TCP retransmission timers (e.g., tcp_syn_retries , tcp_synack_retries ) handle them.

Security aspects are covered, including SYN flood attacks and mitigation techniques using Linux kernel parameters like net.ipv4.tcp_max_syn_backlog , net.ipv4.tcp_abort_on_overflow , and enabling SYN cookies with net.ipv4.tcp_syncookies = 1 .

The article explains the importance of the TIME_WAIT state for preventing old packets from being accepted by new connections and for allowing the passive side to close cleanly, and it outlines ways to tune or reuse TIME_WAIT sockets via net.ipv4.tcp_tw_reuse and net.ipv4.tcp_max_tw_buckets .

It also introduces TCP keep‑alive settings ( net.ipv4.tcp_keepalive_time , net.ipv4.tcp_keepalive_intvl , net.ipv4.tcp_keepalive_probes ) and how applications can enable them with the SO_KEEPALIVE socket option.

Finally, practical socket programming steps are presented: creating sockets, binding, listening, accepting connections, using connect , read / write , and handling closure with proper FIN/ACK sequences, along with relevant sysctl parameters for backlog ( net.core.somaxconn ) and socket options like SO_LINGER for forced RST termination.

TCPnetworkingSocket ProgramminghandshakeConnection Management
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.