Listen to port continuously and dump data to file

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…

Answer

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.

Attribution
Source : Link , Question Author : Cristian Boariu , Answer Author : MariusMatutiae

Leave a Comment