![]() |
jsocketpp 1.0
A cross-platform C++20 socket library.
|
Sockets are a fundamental building block of network programming. Whether you are writing a TCP server or client, understanding the various states a socket transitions through is essential for robust and efficient code. This guide explains the key socket states, why they matter, and their practical implications—particularly for developers using the jsocketpp library.
A socket state describes the current lifecycle phase of a socket (network endpoint) as managed by the operating system. Each state reflects what operations the socket can perform and what system resources it is using.
TCP is a connection-oriented protocol, so its sockets transition through well-defined states as they connect, communicate, and close. The states are defined by the TCP protocol specification (RFC 793).
State | Description | Typical API Calls |
---|---|---|
CLOSED | The socket is not being used. | (Initial state, after close()) |
LISTEN | Server socket is listening for incoming connections. | bind(), then listen() |
SYN_SENT | Client has started a connection; SYN sent, waiting for reply. | connect() |
SYN_RECEIVED | Server has received a connection request (SYN), waiting for confirmation. | (Internal) |
ESTABLISHED | The connection is open; data can be sent and received. | After accept()/connect() |
FIN_WAIT_1 | One side has requested connection close (sent FIN). | close(), shutdown() |
FIN_WAIT_2 | Waiting for remote end to finish closing. | (Internal) |
CLOSE_WAIT | The socket received a close request from the peer; waiting for local close. | (Internal) |
CLOSING | Both sides are closing; waiting for all data to be acknowledged. | (Internal) |
LAST_ACK | Waiting for final acknowledgment of close. | (Internal) |
TIME_WAIT | The socket is closed, but the OS waits before freeing resources to ensure all data is delivered. | (Internal) |
Here’s a simplified diagram of the most common transitions:
UDP and UNIX domain sockets are connectionless, so they don’t follow the TCP state machine. Their states are simpler:
When using the jsocketpp library, you control these states via method calls:
Server Example:
Client Example:
Tip: Understanding socket states will help you debug, optimize, and write safer network code!