Search code examples
socketstcpsshtunnel

SSH: is there a way to specify one port to listen to the server and one to send data to the server?


I learned that TCP requires two ports to work: one to send data to the server, and one to receive data from the server. Is there a way to specify--specifically for ssh--both of those ports? I am under the impression that the local tunnel method is for the outgoing local port and the incoming server port, but not the incoming local port.


Solution

  • With openssh you can create encrypted tunnels to direct traffic from one point to another. You can use -L and/or -R flags to accomplish the job.

    Ex1: You can bind a local port on your client PC that will be forwarded to another machine flowing through the SSH server;

    (ssh user@sshserver -L<local_port>:<remote_ip>:<remote_port>)
    ssh [email protected] -L8080:192.168.1.20:8090
    

    Ex2: You can bind a port on a remote machine that is attached to a port of your local machine flowing through the SSH server;

    (ssh user@sshserver -R<local_port>:<remote_ip>:<remote_port>)
    ssh [email protected] -R8080:192.168.1.20:8080
    

    Ex3: You can bind a local port on your client PC that will be forwarded to a remote port of the SSH server itself;

    (ssh user@sshserver -L<local_port>:<sshserver>:<remote_port>)
    ssh [email protected] -L8080:127.0.0.1:8090
    

    In the first example, executing:

    telnet 127.0.0.1 8080
    

    on the client machine will connect you to 192.168.1.20 on port 8090 (it's a SSH server network!)

    In the second example, the port 8080 will be binded (created) on the machine 192.168.1.20 (it's a SSH server network!) and it's associated to a local port 8080 of the SSH client. So, on 192.168.1.20 you can:

    telnet 127.0.0.1 8080
    

    and you'll be directed to the 8080 of the SSH client machine.

    The third example is like the first, but the remote machine is the SSH server itself, so if you:

    telnet 127.0.0.1 8080
    

    from you client machine, you'll be connected to the port 8090 of the SSH server.