Example

Simple TCP Port-Forwarder

Author: Norman Deppenbroek
Return to REBOL Cookbook

A simple one-to-one port-forwarder in REBOL is very easy and quick to build.

The example below doesn't check on hangups nor errors during transport, but it's easy to extend. Also this example is a 1-to-1 portforwarder and not a one-to-many or many-to-one.

First we need to create a listener (locally listening for incoming sessions), and because we want it to handle 8-bit data, you need /binary as well. We also use /no-wait and /direct here to make it work smoothly.


    server: open/no-wait/binary/direct tcp://:22000
    remote: open/no-wait/binary/direct tcp://127.0.0.1:22

The code above creates a listener (server) on port 22000 and at the same time a client (remote) on port 22 (ssh) towards localhost (assuming you have a daemon running at that port 22). The above example actually opens both ports in one-shot which of course would be different for a multi-serving portforwarder.

We will now wait for one incoming connection on the server-port and close the server-listener directly afterwards to make sure no more clients can connect.


    if server-port: wait server [
        client: first server-port
        close server-port
    ]

We now have two open connections, one from the client to the server and one connection from the application to the forwarded port (22).

A simple UNTIL loop does the IO:


    until [
        io: wait [ 0 client remote ]
        if equal? io client [
            if error? try [insert remote copy client] [break]
        ]
        if equal? io remote [
            if error? try [insert client copy remote] [break]
        ]
    ]

Finally, we close the client and server (not really needed because /core closes all open ports by itself when calling QUIT.)


    close client
    close remote
    quit

Now open your ssh client and connect to localhost port 22000 and your session will be forwarded to your localhost port 22, where the actual sshd is running. (Some ssh daemons detect "the" delay that is cause by using a portforwarder and will warn you for snooping or sniffers, pretty smart :)

This Portforwarder is not perfect and you will discover that when you use this portfowarding method on web pages (which is line-based with reconnects).

Still a nice example to play with. Enjoy.


2006 REBOL Technologies REBOL.com REBOL.net