Jack Li's Blog

How TCP establish and close connection?

TCP establish connection #

sequenceDiagram
	participant Client
	participant Server
	Note over Client, Server: CLOSED
	Note right of Server: LISTEN
	Client->>Server: SYN seq=100
	Note left of Client: SYN-SENT
	Server->>Client: SYN ACK seq=300 ack=101
	Note right of Server: SYN_RCVD
	Note left of Client: ESTABLISHED
	Client->>Server: ACK seq=101 ack=301
	Note right of Server: ESTABLISHED

TCP close connection #

sequenceDiagram
	participant Client
	participant Server
	Note left of Client: ESTABLISHED
	Note right of Server: ESTABLISHED
	Client->>Server: FIN seq=300
	Note left of Client: FIN_WAIT
	Note right of Server: CLOSE_WAIT
	Server->>Client: ACK ack=301
	Note right of Server: LAST_ACK
	Note left of Client: FIN_WAIT2
	Server->>Client: FIN seq=500 ack=301
	Note left of Client: TIME_WAIT
	Client->>Server: ACK seq=301 ack=501
	Note right of Server: CLOSED
	Note left of Client: CLOSED

Why TCP has TIME_WAIT? #

Client normally waits for 2 maximum segment lifetime (MSL) and close the connection. There are two main reason:

  • Ensure all old packets is disapper on the internet.
  • ACK from client might lose due to the network. Therefore, server will resend FIN after timeout. If client closes the connection immediately, client can’t receive the new FIN.