Use iptables to route/alias public IPs to private subnet

  • warning: include(/tmp/fortune.txt): failed to open stream: No such file or directory in /home/mohawksoft/org/www/htdocs/includes/common.inc(1696) : eval()'d code on line 1.
  • warning: include(): Failed opening '/tmp/fortune.txt' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /home/mohawksoft/org/www/htdocs/includes/common.inc(1696) : eval()'d code on line 1.

Suppose you want to route a number of public IP addresses (on a single ethernet device) to specific individual machines on a private subnet. The iptables module can do this for you. Here's how: (PUBLICIP0 and PRIVATEIP0 are place holders for you real values.)

#
# Load iptables module with nat
#
modprobe iptable_nat

#
# Enable forwarding
#
echo 1 > /proc/sys/net/ipv4/ip_forward

#
# Clear out any cruft that may have been picked up.
#
iptables --flush

# We assume "eth0" is your public network device.
# We assume "eth1" is your private network device.
# create an alias for the new IP address

ifconfig eth0.0 $PUBLICIP0 up

#
# Route external traffic to the device
#
iptables -t nat -A PREROUTING -d $PUBLICIP0 -i eth0 -j DNAT --to-destination $PRIVATEIP0

#
# Route internal traffic to the device
#
iptables -t nat -A POSTROUTING -s PRIVATEIP0 -o eth0 -j SNAT --to-source $PUBLICIP0

#
# Allow traffic through firewall
#
iptables -A FORWARD -p tcp -i eth0 -o eth1 -d $PRIVATEIP0 -j ACCEPT