Solution (source code)

= Solution

<Network address translation> lets a <router> join a private <Internet Protocol> address realm to the public <Internet>. On outbound <packets> it replaces the private source <IP address> by a public <IP address>. On returning <packets> it applies the inverse mapping to the destination <IP address>, then forwards to the internal host. Basic <network address translation> changes addresses; the common many-to-one form, <network address and port translation>, also changes the source <transport port> so several internal hosts can share one public <IP address>.<Traditional IP Network Address Translator (Traditional NAT) (RFC 3022)>[§§2.1–2.2 and 3.1–3.3: basic NAT, NAPT and translation phases]{ref}

For example, suppose the public-facing <router> has <IP address> `198.51.100.7`. An internal <TCP> exchange might be translated as follows; the addresses are illustrative:
$$
\begin{aligned}
(10.0.0.2:49152)\longrightarrow(192.0.2.80:80)
&\quad\mapsto\quad
(198.51.100.7:62001)\longrightarrow(192.0.2.80:80).
\end{aligned}
$$
An entry records that traffic returning to external <transport port> 62001 belongs to `10.0.0.2:49152` for this <transport protocol>. The destination on the return path is rewritten accordingly. A second internal host using the same private <transport port> can receive a different public <transport port>. The actual lookup may also use the remote <endpoint>, depending on the mapping and filtering policy.

The <router> must update the <IPv4> header <checksum>, and any affected <TCP> or <UDP> <checksum>: transport checking includes the relevant <IP addresses> as well as the transport header. Bindings may be allocated dynamically and removed after inactivity or observed termination. Traffic for a live exchange must traverse a translator that possesses the binding, or equivalent shared information.

An unsolicited incoming <packet> generally has no dynamic inverse mapping, so exposing a private service usually needs a configured mapping or <port forwarding>. Application data that embeds a private <IP address> can also need special handling. Address translation saves public address space, but changes the addressing visible to the two <endpoints> and can disrupt an exchange if its mapping disappears. Its essential mechanism is
$$
\boxed{\text{rewrite outbound addresses/ports; remember the binding; invert it on replies}.}
$$