Advanced routing with iptables
iptables isn’t just for firewalling; it can also be used for advanced routing techniques:
- Network Address Translation (NAT): Allows multiple devices on a private network to share a single public IP address
- Port forwarding: Redirects traffic from one port to another, often used for making services on your local network accessible from the internet
- Traffic shaping: Controls the flow of network traffic to prioritize certain types of data or prevent network congestion
For example, this code shows port forwarding SSH to a different port:
ken@monster:~$ sudo iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 192.168.1.100:22
ken@monster:~$ sudo iptables -t nat -A POSTROUTING -d 192.168.1.100 -p tcp --dport 22 -j SNAT --to-source :2222
This redirects incoming traffic on port 2222 to port 22 on the machine with IP 192.168.1.100.