10

I use this command to listen to port and dump data to file:

while :  ; do nc -l 0.0.0.0 10000 > log.txt & done

First request works perfect, it's dumped in log.txt but after first request, the nc is no longer listening but stopped.

Can someone point me to what I do wrong?

I just want this to run in the background continuously and log any request from this port to log.txt file...

19

You must add an option to nc. The option depends on the version of nc you are running. For instance, in my case (Kubuntu), the option is -k. From the man page,

-k Forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option.

I cannot promise -k works (unless you are n Ubuntu, of course), you will have to search for something similar. For instance, on my Debian, -k does not exist, but you find:

-q seconds after EOF on stdin, wait the specified number of seconds and then quit. If seconds is negative, wait forever

Edit:

To check that it works, on one pc:

  nc -k -l 0.0.0.0 10000 > out.txt

On a second pc:

  echo Hello | nc IP_address_of_first_pc 10000

Issue the command above a few times, then interrupt the nc command on pc1, check number of lines in out.txt.

  • Thanks. Indeed if I put -k it stays and run in the background but the biggest issue is that only first request is dumped into the log file and no other one... – Cristian Boariu Jan 28 '14 at 12:18
  • @CristianBoariu Sorry, I cannot reproduce this error, it works perfectly on my Ubuntu systems. If I just say nc, I get the reply: This is nc from the netcat-openbsd package. An alternative nc is available in the netcat-traditional package. Do you get the same reply? – MariusMatutiae Jan 28 '14 at 12:42
  • Yes, I receive: "This is nc from the netcat-openbsd package. An alternative nc is available in the netcat-traditional package.". Basically after I put the command from above I go to a browser and do a GET multiple times to that machine but only first one is logged. – Cristian Boariu Jan 28 '14 at 12:44
  • 3
    Are you still using the while? With the -k you shouln't have to use the while. This would be sufficient: nc -l -k 0.0.0.0 10000 > log.txt. And if you want to append to log.txt use nc -l -k 0.0.0.0 10000 >> log.txt. It could also be a buffering problem where log.txt is only written to once in a while. Do a Ctrl+C after sending a couple of messages and see what log.txt contains. – Rik Jan 28 '14 at 12:51
  • @CristianBoariu See my edit,try it like I did.No buffering problem on my systems. – MariusMatutiae Jan 28 '14 at 12:57

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.