Debian Tutorials

Debian Tutorials


Step by step tutorials showing you how to install and configure various applications and services on Debian based Linux distros.

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

Categories


Port forwarding with iptables

Ástþór IPÁstþór IP

In this tutorial we’ll set up a simple port forwarding (NAT) using iptables.

1. Enable ip forward

echo "1" > /proc/sys/net/ipv4/ip_forward

2. Append routing rules to the nat table

iptables -t nat -A PREROUTING -p tcp -s 0/0 -d {local_ip} --dport {local_port} -j DNAT --to {destination_ip}:{destination_port}
iptables -t nat -A POSTROUTING -o eth0 -d {destination_ip} -j SNAT --to-source {local_ip}

3. Now you can access http://{local_ip}:{local_port} and would actually be getting response from http://{destination_ip}:{destination_port}

A working example

If the ip address of your system is 32.64.128.200 and you import the following rules, you would be able to connect to http://32.64.128.200:8080 and actually see the Google search engine because 216.239.59.105:80 is one of Google’s web servers.

iptables -t nat -A PREROUTING -p tcp -s 0/0 -d 32.64.128.200 --dport 8080 -j DNAT --to 216.239.59.105:80
iptables -t nat -A POSTROUTING -o eth0 -d 216.239.59.105 -j SNAT --to-source 32.64.128.200

Comments 4
  • Riaan
    Posted on

    Riaan Riaan

    Author

    I have been working with iptables for a while. Forgot the SNAT and had major issues getting port fwd to a Xen machine up and running. Kicked myself when I read your post.

    You saved me another few hours of not thinking. Thanks from Cape Town South Africa.


  • dan
    Posted on

    dan dan

    Author

    Thank you very much!
    That work very well! You helped a lot 🙂


  • stonehedge_11
    Posted on

    stonehedge_11 stonehedge_11

    Author

    I read your article thought might ask you, i am have dom0 on with one eth0 on public ip, the xen vm is on private ip nat, all works okay.
    but when i try to to put prerouting rule for port 3389 to forward to vm from external it doesnt work.
    firewall on windows vm is off. I can ping windows vm from dom0 and also telnet to 3389.
    any idea ?


  • nrhm
    Posted on

    nrhm nrhm

    Author

    I’ve successfully setup port forwarding using example provided.
    didn’t know that destionation and source for pre and post route differs in that way. Thanks guys.