4 way close
To close a TCP session a four way closing handshake is performed.
1. Host A closes and sends FIN with seq 1000 2. Host B ACK's with ack set to 1001 3. Host B sends its own FIN with seq 500 4. Host A ACK's the last FIN with 501
The connection is then considered to be closed. The active part of closing (the initiator) keeps a state in TIME_WAIT state for 2MSL (MSL). Typically this can be observed in a server that has POP3 service. After the client sends the QUIT call the server replies with a +OK and immediately calls close() thus becoming the active closing end.
It's possible (often in windows) that once the FIN has been ACK'ed that the connection is torn down and the last ACK gets replied to with an RST.
The above closing sequence sees the following states:
1. Host A = FIN_WAIT1 Host B = ESTABLISHED 2. Host A = FIN_WAIT2 Host B = CLOSE_WAIT 3. Host A = TIME_WAIT Host B = LAST_ACK 4. Host A = TIME_WAIT Host B = CLOSED
Check with RFC 793 page 23 (diagram 6) for the accuracy of this finite state machine.