Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forwarding an established TCP connection to another process on another port?

On a Linux machine, you have a daemon that listens on TCP port A. However, it is usually stopped because it is rarely used and takes away a large amount of system resources. Instead, I want to do something like this:

Code an application that listens on port B and does the following as soon as a connection is established: If the daemon is stopped, start it and wait until it listens on port A. Now the difficult part: Connect the client to the daemon in a completely transparent way, i.e. without the client having to reconnect on port A. Also, but this is irrelevant for this question, the application will shut down the daemon when there are no connections for a certain amount of time.

Of course, I could have my application connect to the daemon and pipe all communication. I do not want that. I want some way to forward the established connection to the daemon and then get rid of the connected socket, while the client is now happily connected with the daemon. In some way, I want to give the daemon's process my already connected socket. Is there any way to do something like this?

I'm running Debian, if that's important. I would want to code the application in C/C++, and it's okay to have OS-specific solutions (i.e. use syscalls). Forgive me though, I am not much of a Linux coder, so I am not very familiar with Linux system programming. If there is some obvious way to do it, I simply didn't know.

Of course, I am open for any kind of suggestion.

like image 342
Jesko Hüttenhain Avatar asked Oct 22 '22 02:10

Jesko Hüttenhain


1 Answers

This problem has a pre-existing standard solution, generically known as inetd. It has been around for a long time, first in Unix systems and then Linux.

The more modern implementation is xinetd

like image 101
Jim Garrison Avatar answered Oct 27 '22 10:10

Jim Garrison