How TCP Connection Is Established: Step-by-Step Explanation
A TCP connection is established using a three-way handshake involving
SYN, SYN-ACK, and ACK messages exchanged between client and server. This process synchronizes both ends to start reliable data transfer.Syntax
The TCP connection establishment follows a three-step message exchange:
- SYN: Client sends a synchronize request to start connection.
- SYN-ACK: Server acknowledges and synchronizes back.
- ACK: Client acknowledges the server's response, completing the handshake.
plaintext
Client -> Server: SYN Server -> Client: SYN-ACK Client -> Server: ACK
Example
This example shows a simple Python script using the socket library to create a TCP client that connects to a server, demonstrating the handshake process internally.
python
import socket # Create a TCP socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to server (example IP and port) server_address = ('93.184.216.34', 80) # example.com HTTP port client_socket.connect(server_address) print('TCP connection established with', server_address) # Close the connection client_socket.close()
Output
TCP connection established with ('93.184.216.34', 80)
Common Pitfalls
Common mistakes when establishing TCP connections include:
- Not handling timeouts or retries if
SYNorSYN-ACKpackets are lost. - Ignoring the need for the
ACKto complete the handshake, causing connection failures. - Attempting to send data before the handshake completes, leading to errors.
Properly waiting for the handshake to finish ensures reliable communication.
python
import socket # Wrong: Sending data before connection client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client_socket.send(b'Hello') # Error: no connection yet except Exception as e: print('Error:', e) # Right: Connect first, then send client_socket.connect(('93.184.216.34', 80)) client_socket.send(b'Hello') print('Data sent after connection') client_socket.close()
Output
Error: [Errno 107] Transport endpoint is not connected
Data sent after connection
Quick Reference
| Step | Message | Description |
|---|---|---|
| 1 | SYN | Client requests to start connection |
| 2 | SYN-ACK | Server acknowledges and agrees |
| 3 | ACK | Client confirms and connection is established |
Key Takeaways
TCP connection uses a three-way handshake: SYN, SYN-ACK, and ACK.
The handshake synchronizes both client and server before data transfer.
Always wait for the handshake to complete before sending data.
Handle timeouts and retries to avoid connection failures.
The handshake ensures reliable and ordered communication.