Forwarding a Localhost:Port to an ExternalIP:NewPort
I have figured to do this myself.
2 rules and a flag should be set to achieve this.
Example used here is for telnet localhost XXXX
, should forward packets to Ext.er.nal.IP:YYYY
.
sysctl -w net.ipv4.conf.all.route_localnet=1
This flag unfortunately exists only on quite latest Linux kernels and not available on an old kernel (there isn't any alternate flag as well in the old kernel). Am quite not sure which exact kernel is the flag available from though. I believe it is available on kernel versions 3.XX.
This flag is to consider the loopback addresses as a proper source or destination address.
Source for ip sysctl command.
iptables -t nat -A OUTPUT -p tcp --dport XXXX -j DNAT --to-destination Ext.er.nal.IP:YYYY
The above command will alter the packets that is to localhost:XXXX
with the destination IP as Ext.er.nal.IP:YYYY
iptables -t nat -A POSTROUTING -j MASQUERADE
The command will alter the source IP as the public ip of your machine.
You could make your rules a bit more strict by adding appropriate source and destination IP and interfaces using -s
, -d
, -i
and -o
. See man iptables
.
Thanks to John WH Smith and Wurtel. Suggestions were very helpful.
The easiest way of accomplishing this is to install netcat
and inetd
(Debian has this in openbsd-inetd
).
Add a line to /etc/inetd.conf
:
127.0.0.1:1234 stream tcp nowait root /bin/nc nc ex.ter.nal.ip 1234
Replace the 1234
with the real port number and ex.ter.nal.ip
with the real external IP address. You may need to append .1000
or some larger number to the nowait
option if more than 128 connections per minute need to be made; this is to prevent runaway connections from loading your system unneccessarily.
I also have -q 4 -w 10
as nc
options as that helps in my situation, but you might not need it.
Reload inetd
after modifying the inetd.conf
file.
Doing it this way uses nc
started by inetd
as a relay process, which works quite well.