TCP Protocol (Transmission Control Protocol)
The Transmission Control Protocol (TCP) is a core protocol of the Internet protocol suite. It provides reliable, ordered, and error-checked delivery of a stream of bytes between applications running on hosts communicating via an IP network. TCP is designed for the reliable transmission of data. It guarantees that data arrives in the correct order and without any loss or duplication.
Key Features of TCP
- Connection-Oriented: TCP establishes a connection before data transfer begins, ensuring that both sender and receiver are ready.
- Reliable Delivery: Uses acknowledgment (ACK) and retransmission mechanisms to ensure data arrives correctly.
- Ordered Delivery: Segments are numbered, allowing the receiver to reassemble them in the correct sequence.
- Flow Control: Manages the rate of data transmission to prevent a fast sender from overwhelming a slow receiver.
- Congestion Control: Dynamically adjusts sending rates to avoid overwhelming the network.
TCP Handshake (Three-Way Handshake)
Before data can be exchanged, TCP performs a three-way handshake to establish a connection:
- SYN (Synchronize): The client sends a SYN packet to the server to initiate the connection.
- SYN-ACK (Synchronize-Acknowledge): The server responds with a SYN-ACK packet, acknowledging the client's SYN and sending its own SYN.
- ACK (Acknowledge): The client sends an ACK packet to the server, confirming the connection establishment.
TCP Connection Termination
Connections are typically terminated using a four-way handshake, involving FIN (Finish) and ACK packets from both sides to ensure all data has been sent and acknowledged.
Common TCP Ports
Well-known TCP ports are often associated with specific services:
| Port | Service |
|---|---|
| 20 | FTP (Data) |
| 21 | FTP (Control) |
| 22 | SSH |
| 23 | Telnet |
| 25 | SMTP |
| 53 | DNS (TCP) |
| 80 | HTTP |
| 443 | HTTPS |
API Functions for TCP Programming
When developing network applications on Windows using the Winsock API, you'll commonly use the following functions for TCP sockets:
socket(): Creates a socket.bind(): Assigns a local address and port to a socket.listen(): Puts a socket into a listening state.accept(): Accepts an incoming connection.connect(): Establishes a connection to a remote host.send()/sendto(): Sends data.recv()/recvfrom(): Receives data.closesocket(): Closes a socket.
Important Note on TCP Usage
TCP is ideal for applications where data integrity and order are paramount, such as web browsing (HTTP/HTTPS), email (SMTP/IMAP), and file transfer (FTP). For applications sensitive to latency and where occasional data loss is acceptable (e.g., online gaming, live streaming), UDP might be a more suitable choice.