0

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.

1 Answer 1

1

Following should work

iptables -t nat -A PREROUTING -p tcp -d <your-ip> --dport 80 -j DNAT --to-destination <your-ip>:8080
3
  • 1
    -j REDIRECT --to-port 80 will save you having to duplicate your local IP. Dec 18, 2021 at 10:57
  • @Ginnungagap I was not aware of the REDIRECT target. I learned. Thank you!
    – Bruce
    Dec 20, 2021 at 18:16
  • @AlexD. Thank you for your answer. It works. However, actually, the original iptables command line posted in my question also works. It didn't work because there were other iptables rules affecting this one. I am gonna update my question to reflect the findings.
    – Bruce
    Dec 21, 2021 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.