Is it possible to ‘relay’ a socket?

Posted on

Problem :

I was wondering it it was possible to relay a socket object in either C# or Java? (Preferably C#)

I have lots of little programs i make and host them on my home pc, but my pc is behind a router, so i have to forward a port on my router every time i want to make a new application. So is there a way to send a tcp connection to another application on the same computer? for instance i get a connection in with the first line of text being RELAY::21005 which would then forward that port to localhost:21005 ?

Any help, tutorials, code snippets would be much appreciated. Thank you! 🙂

Solution :

One problem you might face with your suggested solution (first line identifies target port) is that you’ll have to change all of your client programs to send that first line. That’s easy for programs you’ve written yourself but not so convenient if you want to connect to your PC’s web server or ssh daemon etc. It’s not impossible of course, but does make it hard.

I’d suggest your routing server listens on two ports – a control port and a “normal” port (I can’t think of a better name at the moment). You would send control messages to the control port to indicate “until further notice redirect all incoming connections on the normal port to port nnnn”. That avoids having to manipulate client protocols.

I don’t know enough C# to provide advice about a C# solution, but in Java I’d simply do something like:

while (true) {

You’d not be able to scale that easily into thousands of connections…

K I take back my comment, check this out:

Using this requires the port sharing service to be up (it is disabled by default):

The Net.TCP Port Sharing Service is available on all operating systems
that support .NET Framework 3.0, but the service is not enabled by

All of this is only useful to you if you are using WCF services tho.

The easiest approach IMO is to use ssh tunneling. As I wrote in my comment, there are lots of questions on SU that will show you how to do this.

But assuming that you want to program something …

You’ll need to create a client and a server. The client will have threads that call accept on whatever local ports you want to open. When a connection comes to a port, you create another thread that opens a connection to the server and continually sends data over the wire.

The server program listens on a single port, which you open in your firewall. It waits for connections on that port, and when it receives one it opens a connection to the specified local port. Then it shuffles bytes from one to the other.

The only trick is that you have to define a protocol for specifying the destination port in the client-server stream. Simplest approach is to write a two-byte integer at the start of the stream.

Yes, it is possible to relay a socket.
You can use TURN

Some of TURN library/application:

  • pjnath

Leave a Reply

Your email address will not be published. Required fields are marked *