TCP (Transmission Control Protocol) uses handshakes to establish and terminate connections between devices. 

The three-way handshake is used for connection establishment, 

while the four-way handshake is used for connection termination. 


Here's an overview of both:


**Three-Way Handshake (Connection Establishment):**


1. **SYN (Synchronize):** The process begins with the client (initiating device) sending a TCP segment with the SYN flag set to the server (responding device). This segment includes an initial sequence number (ISN) generated by the client.


2. **SYN-ACK (Synchronize-Acknowledge):** Upon receiving the SYN segment, the server responds with a TCP segment of its own. The server sets the SYN and ACK flags, acknowledging the client's SYN segment and providing its own ISN in the acknowledgment number field.


3. **ACK (Acknowledge):** Finally, the client responds with an ACK segment, acknowledging the server's SYN-ACK. The ACK segment also includes an acknowledgment number, which is one greater than the server's ISN. At this point, the connection is established, and both devices can begin exchanging data.





**Four-Way Handshake (Connection Termination):**


1. **FIN (Finish):** When a device wishes to terminate the connection, it sends a TCP segment with the FIN flag set to the other device, indicating that it has no more data to send.


2. **ACK (Acknowledge):** The receiving device acknowledges the FIN segment by sending back an ACK segment, confirming the receipt of the FIN.


3. **FIN (Finish):** If the receiving device also has no more data to send, it can initiate its own connection termination by sending a TCP segment with the FIN flag set to the other device.


4. **ACK (Acknowledge):** Finally, the initiating device acknowledges the FIN from the receiving device by sending back an ACK segment. Once both devices have sent and acknowledged FIN segments, the connection is terminated.



In summary

The three-way handshake establishes a TCP connection by synchronizing sequence numbers and exchanging initial control information, 

While the four-way handshake terminates the connection by exchanging FIN and ACK segments to ensure both devices agree to end the communication session gracefully.