Siddharth
Siddharth

Reputation: 2254

'nc' command stopping even with -k option

I am trying to listen continuously to port 5000 and print the first line of message but the program is stopping after one iteration. I am using the following command for it -

nc -k -l 5000 | head -n 1

I have used -k option with nc but still the program stops after one iteration. What is the problem in this command?

Upvotes: 1

Views: 1289

Answers (1)

peterh
peterh

Reputation: 1

It is not so simple. The second nc could be started only after the full run of the previous. But it can't be done, because nc has a bug: it can't detect if the remote side closes its socket. Thus, the first nc never stops, thus the second can't be started.

The developers of the nc say, that it is an inherent problem of the TCP protocol, my opinion is that they haven't right [but it is only my opinion].

If you want to do practically a script listening on a TCP port, a working solution were to put this head -1 into a script, and calling this script from an inetd.

Some trickier hack could work as well, for example, killing the first nc after the first line, so:

nc -k -l 5000|(read;echo $REPLY;killall -9 nc)

Imho this tools aren't enough stable for productive environment, although they can be very funny. :-)

Upvotes: 2

Related Questions