How to Port Forward using netfilter/iptables

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 10.40.30.123 destination tcp port 80 to tcp port 123 as well as tcp port 443 to tcp port 123

#!/bin/bash
/sbin/iptables -F
 
/sbin/iptables -t nat -A PREROUTING -p tcp -i eth0 -d 10.40.30.123 --dport 80 -j DNAT --to 10.40.30.123:123
 
/sbin/iptables -t nat -A PREROUTING -p tcp -i eth0 -d 10.40.30.123 --dport 443 -j DNAT --to 10.40.30.123:123
 
/sbin/iptables -A FORWARD -p tcp -i eth0 -d 10.40.30.123 --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

One Response to “How to Port Forward using netfilter/iptables”

  1. Matt says:

    To make this work, I needed to add
    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Leave a Reply