I want to route incoming tcp traffic on port 5555 on a Raspberry with Raspbian to another machine and port within the same local network, and make it persistent to reboots.
Context
The objective is that if I access the service on 5555 on localhost, it will load a different port on the remote machine. The ultimate goal is to forward port 53 (DNS) into another machine (non-53 port), but in the meantime, I am testing with http: https://localhost:5555
, it should load https://192.168.250.250:9999
where 192.168.250.250 is a remote machine within my local network (accessible to all local network, ping 192.168.250.250
works).
What I've tried
There's a lot of resources on networking like this. Most rely on IP Forwarding on the router, which won't work in my case as I am trying to redirect ports within hosts in my localhost accessing the machines directly. The others, for port tunnelling, all use the methods below:
iptables
sudo iptables -t nat -A PREROUTING -p tcp --sport 5555 -j DNAT --to-destination 192.168.250.250 --dport 9999
This didn't work. I tried a few variations, including:
sudo iptables -t nat -A PREROUTING -p tcp --sport 5555 -j DNAT --to-destination 192.168.250.250:9999
This didn't work, despite the rule getting registered:
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
DNAT tcp -- anywhere anywhere tcp spt:5555 dpt:9999 to:192.168.250.250
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
I have also installed iptables-persistent
to make it persistent, but it just doesn't redirect in the first place.
I have also tried a variant of the command since I think I may have misunderstood the "source" port as being the destination:
sudo iptables -t nat -A PREROUTING -p tcp -j DNAT --to-destination 192.168.250.250:9999 --dport 5555
After any of these changes, I always run:
sudo dpkg-reconfigure iptables-persistent
sudo netfilter-persistent save
sudo netfilter-persistent restart
To make sure the rules are permanently applied. I have also tried this tutorial to load the configuration on reboot. Nonetheless, again, this just doesn't forward, the permanent side of it is unclear and secondary at this stage.
socat
socat tcp-listen:5555,reuseaddr,fork tcp:192.168.250.250:9999
This works fine. However, it's not persistent. As soon as I cntrl+c the terminal, it stops redirecting.
nc
sudo nc -l -p 5555 -c 'nc 192.168.250.250 9999'
and
sudo nc -l -p 5555 192.168.250.250 9999
Neither work. The first one throws errors (-c not existing). The latter doesn't do anything.
See Question&Answers more detail:
os