In the TCP protocol, ports are used to identify which application or service the incoming data is intended for.
Each TCP communication involves two endpoints, each represented by a unique IP address. However, within each endpoint, there can be multiple applications or services that use TCP to communicate. This is where ports come in.
A port number is a 16-bit number that’s used as part of the header of a TCP packet. The destination port number indicates which application on the receiving endpoint should receive the incoming data.
There are well-known port numbers that are reserved for specific applications, such as port 80 for HTTP traffic and port 21 for FTP traffic. However, any application can be configured to use any port number.
When a client wants to initiate a TCP connection, it sends a SYN packet to the destination IP address with the appropriate destination port number. If the server is listening on that port, it will respond with a SYN/ACK packet, and the connection will be established.
Once the connection is established, both endpoints can exchange data through the port numbers that were established in the initial handshake.