30

I used to run a service on port 25570 I'm now changing it to run on port 25565 but I still want people who try to access it on the old port to have access to the service. So I'd like to forward port 25570 to 25565 on the same machine.

I know there's a lot of questions that talk about forwarding to a different machine but I was wondering if the method is different when using the same machine?

2 Answers 2

35
iptables -t nat -A PREROUTING -p tcp --dport 25570 -j REDIRECT --to-port 25565

This assumes you're not routing traffic for an entire network through this box and that if you were there's no expectation that traffic destined for other hosts will be on that port

4
  • 3
    How can this be undone? Jun 26, 2017 at 17:37
  • 1
    digitalocean.com/community/tutorials/… - ask a separate question Jun 27, 2017 at 1:22
  • @MarcoLavagnino with a similar command, just changing -A (which stands for "Add" ) to -D (which stands for "Delete")
    – istepaniuk
    Sep 11, 2021 at 17:08
  • As the answer writes, this is dangerous as-is as if you also are using the host for doing any kind of IP forwarding things (like NAT for another server through this), this solution will redirect all the NATed connections to the other (local) port. I discovered this recently while doing something similar. If you have such a setup, you could fix it by adding more qualifiers to the rule, for example adding the explicit ethernet interface name if the WAN port for incoming connections from the internet, so outgoing NATed connections won't be redirected generally.
    – BjornW
    May 4, 2023 at 12:38
26

It is worth noting the the accepted answer only applies for other network hosts connecting to the machine running iptables. It does not redirect the port for clients running on the iptables machine trying to connect to port 25570 (for example).

These entries will forward the port for connections coming from the network or from the local host running the services.

sudo iptables -t nat -I PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443
sudo iptables -t nat -I OUTPUT -p tcp -o lo --dport 443 -j REDIRECT --to-ports 8443
1
  • 2
    Thanks for this! Without this addition I wouldn't have been able to get my Vagrant box to request the site it was serving using the same port internally (to that of the host machine) i.e. HOST = localhost:9000 and now GUEST = localhost:9000 (which routes to :80)
    – Pebbl
    Sep 4, 2015 at 10:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .