How does the process of replacing the incoming message (say from stackexchange) to the router, and modifying the header with my PC IP happen? How does the router know which IP to insert there? Is there a MAC address of my device hidden somewhere?
How does the process of replacing the incoming message (say from stackexchange) to the router, and modifying the header with my PC IP happen?
Since you're referring to Stack Exchange, you seem to mean source NAT (NAPT) which is used for private-to-public translation, especially for Internet access.
For a new outgoing connection, the NAT router creates an entry in its translation table with
- transport-layer protocol (TCP or UDP)
- original source IP address
- original source port
- destination IP address
- destination port
- translated source IP address (only necessary for a pool of public addresses, uses the router's WAN IP otherwise)
- translated source port
Then it translates
source IP:source port to
translated IP:source port and forwards the packet to WAN.
For incoming WAN packets, the NAT router checks if there's a matching connection in its translation table. If yes, it reverses the translation (now for
destination IP address:port) and forwards the packet to LAN
How does the router know which IP to insert there?
The router uses the public IP address (or pool) that is configured for the NAT policy. (I'm simplifying a bit, NAT is sometimes also used for overlapping private-to-private networks as well.)
Is there a MAC address of my device hidden somewhere?
Each interface in a MAC-based network like Ethernet requires a unique MAC address for forwarding on the data link layer (switching). Bare IP addresses cannot be used and require resolving each IP address to a MAC address (ARP for IPv4 or NDP for IPv6).