I usually have this command to do the local port mapping
socat TCP4-LISTEN:80,fork,reuseaddr TCP4:127.0.0.1:8080
So whenever the client talks to port 80 of my machine, it talks to port 8080 actually.
It is actually a proxy.
I am wondering if I could use iptables, instead of running a proxy, to achieve the same goal. Like, I tried the following command, which doesn't work.
iptables -t nat -A PREROUTING -d <my-ip> -p tcp --dport 80 -j DNAT --to-destination :8080
UPDATE
The command above should've worked, but it didn't, because there were other iptables
rules affecting it.
So without other rules, the following 3 commands all work.
iptables -t nat -A PREROUTING -d <my-ip> -p tcp --dport 80 -j DNAT --to-destination <my-ip>:8080
iptables -t nat -A PREROUTING -d <my-ip> -p tcp --dport 80 -j DNAT --to-destination <my-ip>:8080
iptables -t nat -A PREROUTING -d <my-ip> -p tcp --dport 80 -j DNAT --to-destination <my-ip>:8080
Thank you @AlexD. After read your answer, I started over the test much more carefully, and figured out this. Also thanks @Ginnungagap, the REDIRECT
target you showed me is more simple and straightforward.
New question
I now have a new question based on the test result, which looks like a SNAT
or MASQUERADE
target is not necessary in my case, why? I thought a SNAT
is mandatory for a DNAT
rule.