45

I am executing the following command from a script:

echo '{"hostUp": true}' | sudo /usr/local/bin/netcat localhost 8001

However, the netcat client stays open indefinitely. How can I close the connection once this data has been sent?

Chris Stryczynski
  • 1,176
  • 2
  • 15
  • 23
Justin Meltzer
  • 621
  • 1
  • 9
  • 18

6 Answers6

30

Both other answers -c and -q given are correct in the right context, but it may help to summarize why there are multiple answers and give a more general solution.

These different options do the same thing but are different implementations of netcat:

  • -c GNU implementation of netcat
  • -q OpenBSD implementation of netcat.
  • -w (other?) OpenBSD implementation of netcat.

Some versions require an int to specify the number of seconds to wait before quitting for the -q and -w options. This int must be > 0 or >= 0, depending on the version.

If you are implementing something across multiple machines and are not sure they use the same implementation of netcat, you might consider wrapping your netcat call with the timeout program to kill netcat after a few seconds.

timeout 5 echo '{"hostUp": true}' | netcat localhost 8001

This approach is a bit clumsy because it puts an upper limit on the execution of netcat regardless of whether or not if it is sending data successfully, but if you are sending a small amount of data and have a few seconds to spare then this should work with any netcat implementation.

7yl4r
  • 403
  • 5
  • 9
  • 1
    `timeout 5 echo '{"hostUp": true}' | netcat localhost 8001` doesn't work, but `echo '{"hostUp": true}' | timeout 5 netcat localhost 8001` does. Is that perhaps what you meant? – Christian Fritz May 15 '21 at 17:49
8

You can use -q parameter, but it will cause the netcat server to be closed also.

$ echo '{"hostUp": true}' | sudo /usr/local/bin/netcat -q 5 localhost 8001    
cuonglm
  • 2,346
  • 2
  • 15
  • 20
4

On Ubuntu 18.04 server I had to use the following: (found in man pages)

echo '{"hostUp": true}' | sudo /usr/local/bin/netcat -N localhost 8001

Obviously the -N is similar to -q or -c on other distros

RalfFriedl
  • 3,008
  • 4
  • 12
  • 17
3

In my case, the copy of netcat that I was using on my Mac installed via Homebrew (v 0.7.1) did not have a -q option, but I was able to use the -c option to close on STDIN EOF and put the whole command in a loop:

while true ; do printf 'HTTP/1.1 200 OK\r\n\r\ncool, thanks' | netcat -l -c -p 8888 ; done
jmaxyz
  • 131
  • 3
2

On Windows it is -w 5 (seconds of wait before close with a min. of 1 sec)

Example sending "hello" in udp to a broadcast address on Windows and closing after 1 second:

echo hello|nc -w 1 -u 10.0.30.255 -p 4000 5000
Roel
  • 33
  • 5
1

for me -N is working on ubuntu 20.04 for this exact purpose.

bhakku
  • 11
  • 1