To make the transport services reliable, TCP hosts must establish a connection-oriented session with one another. Connection establishment is performed by using the three-way handshake mechanism. A three-way handshake synchronizes both ends of a network by enabling both sides to agree upon original sequence numbers.
This mechanism also provides that both sides are ready to transmit data and learn that the other side is available to communicate. This is essential so that packets are not shared or retransmitted during session establishment or after session termination. Each host randomly selects a sequence number used to track bytes within the stream it is sending and receiving.
The three-way handshake proceeds in the manner shown in the figure below −
The requesting end (Host A) sends an SYN segment determining the server's port number that the client needs to connect to and its initial sequence number (x).
The server (Host B) acknowledges its own SYN segment, including the servers initial sequence number (y). The server also responds to the client SYN by accepting the sender's SYN plus one (X + 1).
An SYN consumes one sequence number. The client should acknowledge this SYN from the server by accepting the server's SEQ plus one (SEQ = x + 1, ACK = y + 1). This is how a TCP connection is settled.
While it creates three segments to establish a connection, it takes four segments to terminate a connection. During a TCP connection is full-duplex (that is, data flows in each direction independently of the other direction), each direction should be shut down alone.
The termination procedure for each host is shown in the figure. The rule is that either end can share a FIN when it has finished sending data.
When a TCP receives a FIN, it should notify the application that the other end has terminated that data flow direction. The sending of a FIN is usually the result of the application issuing a close.
The receipt of a FIN only means that there will be no more data flowing in that direction. A TCP can send data after receiving a FIN. The end that first issues the close (example, send the first FIN) executes the active close. The other end (that receives this FIN) manages the passive close.