How a router decides destination of packet?

I have a basic networking question. Two PCs are communicating on a WLAN. Both the PCs are behind routers or modems.

Both the PCs have the same public IP. That public IP is most of the time is either of the router or of the modem. There can be more then one PC behind those routers and modems. How are the PCs are communicating? I can understand that packets can reach those routers or modems and then the Internet, but what after that? In the packet, the destination IP is set as the public IP. When the packet returns, how does the router or modem decide where to send the packet? Can anybody explain me this please.


Most of the mechanics behind this mystery is NAT-masquerading:

  • Your PC communicates with outside

for instance your PC is on a private network, with IP 10.1.2.3.
Your router remembers the PC IP/port, and that it initialized a connection to a remote IP/port (WAN). Thus, when there is a reply on the same channel, the router forwards back the packet to the PC, on its LAN side.

  • An external device communicates with your PC

In this case, the ext. device initializes the connection, and thus the router doesn't know to which 10.x.x.x client it is supposed to forward the packet.
This is why the router needs a specific settings that says, for instance if your PC happens to be a Web server (http port)

  HTTP (WAN) ==> (LAN) 10.1.2.3:80

that says, the packets coming on the HTTP port go to the internal LAN address 10.1.2.3 (your PC) on port 80.