Why do we need both source and destination port numbers in transport layer protocols such as TCP or UDP? What is the purpose for having both?
3 Answers
Just as MAC addresses are layer-2 addresses, and IP addresses are layer-3 addresses, port numbers are layer-4 addresses. When the transport layer wants to reply to a layer-4 request, it must have the address (port) to which it should reply.
When a PC sends an HTTP (TCP port 80) request to to an HTTP server, the PC uses an ephemeral TCP source port and the HTTP server's TCP port 80 as the destination port. The HTTP server replies back to the PC's ephemeral port, and it gets that port number from the source port of the PC's request.
-
So we need both ports so that both the client and server can communicate correct?– SmreksNov 11, 2015 at 23:54
-
Yes. In all the different layers, the headers have both source and destination address. This facilitates the typical request/reply used in communications. It doesn't hurt anything to have the source address if no reply is requested or needed, but the headers are designed so that they can be used to give the destination host the necessary information for round-trip communication.– Ron Maupin ♦Nov 11, 2015 at 23:58
-
1A common misunderstanding amongst neophytes is that the port number on the client must be the same as the port number on the server. Why this is not true (and usually impossible to accomplish) is left as an exercise to the reader.– dr_Nov 12, 2015 at 9:53
The destination TCP port tells which service on the host is needed: 80 is usually http, 22 ssh, 25 mail, ...
But one source can connect several times to the same service: for instance, I can ssh twice to mybox.example.net. As the destination port would be 22, I need different source ports to distinguish the two connections. Usually source ports are chosen randomly by the client.
If you take the main parameters of a socket in our example: src IP, dst IP, protocol, src Port, dst Port, only src Port change between two ssh connections to the same host.
That is why we need both a source port number and a destination port number.
I'll give you an example to explain a little more, if you are using your browser to browse a website, Your PC IP address will be the source IP address and the web server on the other side will be the destination IP, your web browser will put port 80 "http default" as the destination port and will generate a source port number and send it to the web server, the web server will reply to your PC using the same port your pc generated earlier, if source ports weren't exist you wouldn't be able to use multiple applications at the same time.