Since TCP is a connection-oriented protocol, a connection needs to be established before two devices can communicate. TCP uses a process called three-way handshake to negotiate the sequence and acknowledgment fields and start the session. Here is a graphical representation of the process:
As the name implies, the three way handshake process consists of three steps:
- Host A initiates the connection by sending the TCP SYN packet to the destination host. The packet contains the random sequence number (e.g. 5432) which marks the beginning of the sequence numbers for data that the Host A will transmit.
- The Server receives the packet and responds with its own sequence number. The response also includes the acknowledgment number, which is Host A’s sequence number incremented by 1 (in our case, that would be 5433).
- Host A acknowledges the response of the Server by sending the acknowledgment number, which is the Server’s sequence number incremented by 1.
Here is another picture with the numbers included:
After the data transmission process is finished, TCP will terminate the connection between two endpoints. This four-step process is illustrated below:
- The client application that wants to close the connection sends a TCP segment with the FIN (Finished) flag set to 1.
- The server receives the TCP segment and acknowledges it with the ACK segment.
- Server sends its own TCP segment with the FIN flag set to 1 to the client in order to terminate the connection.
- The client acknowledges the server’s FIN segment and closes the connection.