Search code examples
linuxubuntudebianiptablesportforwarding

iptable for port forwarding


I want to redirect all trafic coming to my Linux (192.168.1.34) on the port 22 to another address

So I used the following iptable command

sudo iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 192.168.1.239:22

the command does not return error.

But when I try to open ssh session from a PC (192.168.1.133) to my linux (192.168.1.34), the ssh session is not opened. It looks like the ssh trafic is not redirected to (192.168.1.239)

If I open the ssh session directly from the PC (192.168.1.133) to the (192.168.1.239), then the session is opened


Solution

  • First, make sure the NAT host has IP forwarding enabled:

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

    Second, all your hosts are on the same subnet which means, the SSH traffic from 192.168.1.239 back to your client (192.168.1.133) is NOT routed via 192.168.1.34.

    So you can either:

    1. use both DNAT and SNAT, or
    2. use different subnets for your hosts.