The Linux Programming Interface

(nextflipdebug5) #1
Sockets: Advanced Topics 1269

Figure 61-3 and later similar diagrams are intended to illustrate the exchange
of TCP segments between two endpoints. An implicit time dimension is
assumed when reading these diagrams from top to bottom.

61.6.3 TCP State Machine and State Transition Diagram


Maintaining a TCP connection requires the coordination of the TCPs at both ends
of the connection. To reduce the complexity of this task, a TCP endpoint is mod-
eled as a state machine. This means that the TCP can be in one of a fixed set of states,
and it moves from one state to another in response to events, such as system calls by
the application above the TCP or the arrival of TCP segments from the peer TCP.
The TCP states are the following:

z LISTEN: The TCP is waiting for a connection request from a peer TCP.
z SYN_SENT: The TCP has sent a SYN on behalf of an application performing
an active open and is waiting for a reply from the peer in order to complete the
connection.
z SYN_RECV: The TCP, formerly in the LISTEN state, has received a SYN and
has responded with a SYN/ACK (i.e., a TCP segment with both the SYN and ACK
bits set), and is now waiting for an ACK from the peer TCP in order to com-
plete the connection.
z ESTABLISHED: Establishment of the connection to the peer TCP has been
completed. Data segments can now be exchanged in either direction between
the two TCPs.
z FIN_WAIT1: The application has closed the connection. The TCP has sent a FIN
to the peer TCP in order to terminate its side of the connection and is waiting
for an ACK from the peer. This and the next three states are associated with an
application performing an active close—that is, the first application to close its
side of the connection.
z FIN_WAIT2: The TCP, formerly in the FIN_WAIT1 state, has now received an
ACK from the peer TCP.
z CLOSING: The TCP, formerly awaiting an ACK in the FIN_WAIT1 state,
instead received a FIN from its peer indicating that the peer simultaneously
tried to perform an active close. (In other words, the two TCPs sent FIN seg-
ments at almost the same time. This is a rare scenario.)
z TIME_WAIT: Having done an active close, the TCP has received a FIN, indicating
that the peer TCP has performed a passive close. This TCP now spends a fixed
period of time in the TIME_WAIT state, in order to ensure reliable termina-
tion of the TCP connection and to ensure that any old duplicate segments
expire in the network before a new incarnation of the same connection is created.
(We explain the TIME_WAIT state in more detail in Section 61.6.7.) When this
fixed time period expires, the connection is closed, and the associated kernel
resources are freed.
z CLOSE_WAIT: The TCP has received a FIN from the peer TCP. This and the
following state are associated with an application performing a passive close—
that is, the second application to close the connection.
Free download pdf