Score:0

How to make local port mappings with iptables

in flag

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.

Score:1
jp flag

Following should work

iptables -t nat -A PREROUTING -p tcp -d <your-ip> --dport 80 -j DNAT --to-destination <your-ip>:8080
Ginnungagap avatar
gu flag
`-j REDIRECT --to-port 80` will save you having to duplicate your local IP.
Bruce avatar
in flag
@Ginnungagap I was not aware of the `REDIRECT` target. I learned. Thank you!
Bruce avatar
in flag
@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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.