Simple way to create a tunnel from one local port to another?

With socat on the server:

socat tcp-listen:8001,reuseaddr,fork tcp:localhost:8000

By default, socat will listen on TCP port 8001 on any IPv4 or IPv6 address (if supported) on the machine. You can restrict it to IPv4/6 by replacing tcp-listen with tcp4-listen or tcp6-listen, or to a specific local address by adding a ,bind=that-address.

Same for the connecting socket you're proxying to, you can use any address in place of localhost, and replace tcp with tcp4 or tcp6 if you want to restrict the address resolution to IPv4 or IPv6 addresses.

Note that for the server listening on port 8000, the connection will appear as coming from the proxy (in the case of localhost, that will be localhost), not the original client. You'd need to use DNAT approaches (but which requires superuser privileges) for the server to be able to tell who's the client.


Using ssh is the easiest solution.

ssh -g -L 8001:localhost:8000 -f -N [email protected]

This forwards the local port 8001 on your workstation to the localhost address on remote-server.com port 8000.
-g means allow other clients on my network to connect to port 8001 on my workstation. Otherwise only local clients on your workstation can connect to the forwarded port.
-N means all I am doing is forwarding ports, don't start a shell.
-f means fork into background after a successful SSH connection and log-in.
Port 8001 will stay open for many connections, until ssh dies or is killed. If you happen to be on Windows, the excellent SSH client PuTTY can do this as well. Use 8001 as the local port and localhost:8000 and the destination and add a local port forwarding in settings. You can add it after a successful connect with PuTTY.


Using the traditional nc is the easiest solution:

nc -l -p 8001 -c "nc 127.0.0.1 8000"

This version of nc is in the netcat-traditional package on Ubuntu. (You have to update-alternatives or call it nc.traditional.)

Note that in contrast to ssh this is not encrypted. Keep that in mind if you use it outside one host.