Visual C++ Network: How does a TCP connection close?
Q: How does a TCP connection close?
A: It takes three packets to start a connection, but it takes four to close it. As with the connection establishment, termination is also two-way. But the difference is, each closure is independent of the other. Once the connection is closed one way, the connection is then said to be half open. Now lets see how the termination sequence is.
When one end decides there is nothing more to send, it sends a 'FIN' packet (a packet with 'FIN' flag on) to the other end. The other end sends an acknowledgement packet ('ACK') for the 'FIN' it received. Once this happens, one way is closed, and the connection is now half open. The other end meanwhile sends all the data if any, and when it is over it sends a FIN packet and this packet is acknowledged. Now the connection is effectively closed and no communication can take place between the end points.
It would be better to note that, the end that initiates termination first is said to be performing an active close, while the other end, a passive close. However, it is possible to close simultaneously i.e performing a close without getting the 'FIN' from the other end. In such case both ends are said to be doing an active closure.
Note: A 'FIN' packet is send when the application calls 'closesocket()' or 'shutdown()'.