How to Port Forward using netfilter/iptables

June 21, 2011

This is a quick example of how to write a quick bash script to use iptables to configure netfilter for port forwarding purposes. This sometimes comes in handy if you need to forward a non standard service/port through a standard port, also a slew of other use cases.

Below is an example bash script port forwarding on eth0 for IP destination tcp port 80 to tcp port 123 as well as tcp port 443 to tcp port 123

/sbin/iptables -F
/sbin/iptables -t nat -A PREROUTING -p tcp -i eth0 -d --dport 80 -j DNAT --to
/sbin/iptables -t nat -A PREROUTING -p tcp -i eth0 -d --dport 443 -j DNAT --to
/sbin/iptables -A FORWARD -p tcp -i eth0 -d --dport 123 -j ACCEPT

*Make sure the iptables service is started, then run the script

*Beware /sbin/iptables -F will flush your existing rules if you have any so make sure you run
/sbin/iptables -L -v -n –line-numbers and see. If you have any rules add them to the script.

*If you are using a different src and dst IP you will want to enable ip forwarding:
echo 1 > /proc/sys/net/ipv4/ip_forward

Comments are closed.