12

I use netcat to run a simple server like this:

while true; do nc -l -p 2468 -e ./my_exe; done

This way, anyone is able to connect to my host on port 2468 and talk with "my_exe".
Unfortunately, if someone else wants to connect during an open session, it would get a "Connection refused" error, because netcat is no longer in listening until the next "while" loop.

Is there a way to make netcat behave like a multi-threaded server, i.e. always in listening for incoming connections? If not, are there some workarounds for this?

  • You can use socat – sivann Sep 22 '16 at 11:27
18

you are using the wrong tool for the task: use something like ucspi-tcp, especially tcpserver:

tcpserver waits for incoming connections and, for each connection, 
runs a program of your choice.
  • 1
    Where has this been all my life?! – Sridhar Sarnobat Jan 14 '17 at 2:01
  • Thanks @akira, can you provide the example? – Sabrina Jan 21 at 2:18
3

Although you didn't mention the operating system you're using, I'll assume it's Linux or Unix based on the syntax of your shell command example.

If your system is running xinetd (or its predecessor inetd), you can use that software to listen for a connection on the port of your choice, and run an executable to respond. With xinetd/inetd, you have the option of allowing multiple concurrent connections, each served by a separate instance of your executable.

-2

you could likely just background the process (then it doesn't wait for a return before stepping to the next loop) with an '&' such as:

while true; do nc -l -p 2468 -e ./my_exe &; done
  • 7
    That's going to spawn loads of subprocesses and crash the system.... – jackweirdy Aug 2 '12 at 18:42
  • 5
    And, only the first invocation will work; every succeeding one will fail because there's already a server socket on port 2468. – Daniel Griscom Mar 27 '16 at 22:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.