How to send only one UDP packet with netcat?

Janne H picture Janne H · Mar 14, 2012 · Viewed 210.1k times · Source

I want to send only one short value in a UDP packet, but running the command

echo -n "hello" | nc -4u localhost 8000

I can see that the server is getting the hello stuff but I have to press Ctrl+c to quit the netcat command.

How can I make it quit after sending hello?


Sorry, for the noise, I re-read the man page and found the -q option.

 echo -n "hello" | nc -4u -q1 localhost 8000

works (it quits after 1 second).

For some reason it does not work with -q0.

Answer

Peter Eisentraut picture Peter Eisentraut · May 15, 2013

If you are using bash, you might as well write

echo -n "hello" >/dev/udp/localhost/8000

and avoid all the idiosyncrasies and incompatibilities of netcat.

This also works sending to other hosts, ex:

echo -n "hello" >/dev/udp/remotehost/8000

These are not "real" devices on the file system, but bash "special" aliases. There is additional information in the Bash Manual.