<aside> 💡
In this section, we’ll discuss the purpose of Source NAT (SNAT) and observe how SNAT affects our packets through three ****small experiments.
</aside>
In the previous section (@6. Understanding the Relationship Between iptables, Docker, and Linux Bridge), we mentioned that iptables is a user-space tool that allows users to configure and interact with the Linux kernel’s Netfilter system.
In common use cases, users employ iptables to define firewall rules or packet translation rules.
Among these, Source NAT (SNAT) is a feature implemented by Netfilter that modifies the source IP address or port of packets, allowing internal network hosts to communicate with external networks using a single public IP address.
In other words, iptables provides the configuration interface, while the Netfilter subsystem in the Linux kernel actually performs the SNAT operation and packet transformation.
In iptables, there are two built-in NAT targets used for Source NAT (SNAT), but they differ in how the source IP is set:
SNATBehavior: Replaces the source IP of outgoing packets with a specific, static public IP address.
When to use:
Performance: Slightly more efficient than MASQUERADE (no extra lookups needed).
Example
$ iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 203.0.113.5:8877
The above command demonstrates how to modify the IP address and port number using iptables.
When the source address is 192.168.1.0, any packet sent out through the eth0 interface will have its source rewritten to 203.0.113.5:8877.
Note:
-to-source, iptables will still accept and apply the rule successfully. However, the returning packets will not be able to reach their destination.-to-source, the kernel will automatically assign a random port number from the range 1024–64512.MASQUERADE