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?
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?
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.
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
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
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
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