Closing a connection means "No more data to send" but it should be from both end. In complete and graceful closing one end tells the other end that it does not have any data to send while other ends tells that it also don't have any thing to send then both starts process of closing the connection.
Simply in graceful completion of a dialogue one can not disconnect the call without acceptance of other party. Same is applied in TCP graceful termination.
Technically speaking TCP termination is a 4-Way Handshake Process, some time also seen as 2-sets of 2-ways Handshake. FIN segment is sent to initiate termination. Let's see how it happens
|TCP Connection Termination|
Here in order to explain connection termination we have considered two hosts one of them acting as client and other as server.
1) Both Hosts are in ESTABLISHED state, Now Host-A (acting as client)comes to know it does not have more data to send. It triggers FIN segment by setting FIN flag and goes in FIN-WAIT-1.
Now Host-A can't push more data toward Host-B.
2) On receiving FIN Host-B goes in CLOSE-WAIT state and acknowledges with ACK. Now it does not means that Host-B stops the connection immediately, there might me the case Host-B may have some more data to send. Host-B shall send data if any.
While on receiving ACK in response of FIN, Host-A goes in FIN-WAIT-2, Waits for all data from Host-B to arrive until Final FIN from Host-B is arrived.
3)If there is no data to send from Host-B then it trigger FIN from its own end indicating that Host-B also ready to close and goes in LAST-ACK state. Means waiting for last acknowledgement from Host-A because TCP is reliable protocol.
4)After receiving FIN from Host-B, Host-A triggers final ACK and goes into TIME-WAIT. TIME-WAIT is state where Host-A wait for 2MSL before going to CLOSED state. On receiving final ACK from Host-A, Host-B goes in CLOSED state where no more data is accepted.
MSL is maximum segment lifetime for which a segment can exist in network. It is 120 seconds. Here Host-A waits for 2 MSL because in any case if final ACK got lost (1-MSL) and waiting for retransmitted FIN to arrive at Host-A. This is very rare.
FINAL ACK IS LOST
Below diagram depicts one of the case where final ACK got lost. RESET. As we already know that RESET segment is used to make thing synchronized in tricky situation let see how it helps here. Diagram is self explanatory.
|Scenario where Final ACK is Lost|
Simultaneous TCP Connection Termination Request
There could be a case that where both hosts initiates termination (FIN) segment at the same time. Below diagram depicts how things happen.
|Simultaneous TCP Connection Termination|
Your Comments /Suggestions and Questions are always welcome. We would try to clarify doubts with best of our knowledge. So feel free to put Questions.