Nat – How do ephemeral ports work through NAT

nat;networking

I think I'm correct in saying that:

  1. OSes generally use the IANA ephemeral port range of 49152 to 65535.
  2. Apps generate a random ephemeral port to establish a connection from the client to the server.
  3. NAT translates IP addresses, usually private-public.

So, how do ephemeral ports work with NAT?

As far as my understanding goes (I'm sure that I'm missing something), shouldn't there be a possibility (higher on larger networks) that ephemeral ports could conflict in the network or on the server if, for example, two or more clients happen to generate and use the same random ephemeral port to connect via NAT?

Best Answer

There is no conflict because connected socket is defined by the following four values:

  1. Source IP
  2. Destination IP
  3. Source port
  4. Destination port

Two different clients means there is at least one different value which is the source IP even when accessing the same server/service.

To relate this with NAT, the router/gateway will create a new mapping for each new connection. This mapping is saved to be able to return further responses to user and to use it while the connection is valid. This is called connection tracking in terms of Linux netfilter.