This section goes a bit deeper into how network communication functions regarding Ports. If you want to understand how Address Translation works in depth then you have to understand a few more things about ports than what we previously discussed.
IP packets always have a source IP address (who sent the package) and a destination IP address (who is the recipient of the package). The same thing goes for the Transport Protocols which also require both a source and a destination port.
Each UDP or TCP message has a destination port, meaning which service or program that the message is intended for. Maybe the message is intended for a Web Server listening on port 80/TCP, or perhaps a DNS Server listening on port 53/UDP.
But all UDP and TCP messages also have a source port. The source port is most often randomly picked by the computer. The source port can be used by routers and firewalls in the network to distinguish between different communication flows or sessions since each session will have a different random source port associated with it.
For example, let’s say that you open two web browsers at the same time on your computer. Then you browse simultaneously from both web browser to the same web page on the Internet. You will now have two sessions from your computer’s IP address to the IP address of the web server. Both sessions are also going to the same destination Port, 80/TCP.
There will be two replies coming back from the Web server, one reply for each web browser on your computer. But how will your computer know which browser that should receive which reply?
The answer is in the random source port that the computer picks for each traffic flow. An ongoing communication between two devices is called a session. The OS of the computer will remember some details for each session, including which program that was involved, what IP addresses that the communication is going between, and what source and destination port that is used. In this case, two web browsers have a session each.
When the replies are coming back from the web server the computer can look at those ports and compare them with the session table in memory to see which web browser that should receive which reply.
Also note in the two pictures above that the source and destination IP addresses and Ports swap places for the return traffic. This is because the return traffic is coming from the web server and is going to your computer.
Your computer is browsing from a random TCP source port to the destination port 80/TCP of the web server. The reply is coming from port 80/TCP on the web server and is going to the random destination port that your computer picked.