'How NAT is able to change port numbers?

Based on my knowledge , I believe following statements are true.

  1. Router can only redirect packet and can interact upto network(internet layer) only.
  2. NAT maps the private ip to public ip. It uses a NAT table in which source private ip is mapped to public ip and also source port is changed with new source port.

My question is regarding NAT function for port . How NAT , that works in router can change something that relates to transport layer(port)? i.e when the private system sends the source port , how NAT is able to change it with new port before sending it to internet.

I am missing something or maybe I am wrong somewhere . Would appreciate the help.

Thanks



Solution 1:[1]

NATs intercept outgoing IP packets (including UDP and TCP) from nodes on the NAT's internal network and can modify the source IP and source port in the UDP and TCP header in place. It will update other fields in the header as well (i.e. checksum).

Similarly, for incoming packets, the NAT will change the destination IP/port after finding an entry in its port mapping table that was created from a previous outbound packet or connection.

As to "how" - it just does. It literally reconstructs a new UDP/TCP/IP header using the exact same payload of what it received. The NAT is registered as the gateway device on the LAN, so all packets bound for the internet will be sent to the NAT's MAC address - if what you are wondering is how the NAT captures the packets to begin with.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1