The client and server are done – they’ve exchanged data and now are ready to close the TCP session…now what ?
Well, much like TCP’s handshake protocol to setup a client-server connection, TCP also has a process to effectively end the connection. Note that either client or server can start to end the connection. In this post, I’ll have the client initiate the TCP connection termination – IE the “close.”
TCP Close Process
The TCP close process is a 4 packet sequence between the client and server that can be initiated by either one. Here’s what the TCP close process diagram looks like.
Note: In the below Wireshark example, the client is 192.168.1.105 and the server is 22.214.171.124.
Packet 1 – Either the client or server starts the close process by sending a TCP Fin packet. For this example, assume the client initiates the TCP close. In the below figure, we see a Wireshark decode of Wireshark packet # 280, which is the first packet sent by the client to initiate the TCP close. Key points include the FIN and ACK flags being set and the capture of the sequence and acknowledgement numbers.
Packet 2 – The server Ack’s the Fin packet but does not increment the Ack number because the server does not expect any more data packets. Wireshark packet # 283 shows this in detail.
Packet 3 – The server send’s the Fin packet to initiate the server side of the TCP close and we can see this in detail in Wireshark packet # 284.
Packet 4 – Finally, the client Ack’s the Fin packet and again we can see that in Wireshark packet # 285.
TCP Close Table
There are a couple of unique things in the TCP close process with respect to Ack bits and sequence numbers that are interesting.
- The client and server have been exchanging information so the Seq# and Ack# have been incrementing throughout the session and have reached certain numbers. There is no requirement for a specific Seq# or Ack# to begin the TCP close.
- In the TCP close table, the ACK bits in packet 1 and 3 are not specific to closing TCP sessions, but are needed because part of the general TCP process is to send Ack’s back to the sender with the Ack number set to the expected next sequence number.
- In packet 2, the server Ack’s the client Fin bit but notice that the Ack # is not incremented by 1. This means that the server is telling the client that it does not expect to receive any more data packets (since it’s received a Fin bit and the closing process has started.
- The Sequence and Acknowledgement numbers increment by 1, this is another clue that we’re in the TCP close process.
A key part in understanding the TCP close process is to understand the TCP finite state machine. This link provides a good review.
With this, the TCP session is now closed.