How to redirect a udp response with netcat

netcat

Similar question to How to get a udp response with netcat except the OP was satisfied with using nc interactively (and I don't have the reputation to comment yet!)

I need to be able to code some bash script and deal with the response. How should the code below be changed to get the response in the file response.txt or otherwise capture the response for later lines of code in bash?

echo "request" | nc -u 1.1.1.1 9999 > response.txt

The server might take a few seconds or even minutes to generate the response and reply. When I try the following, I'm returned to the command prompt immediately and response.txt is empty.

echo "request" | nc -u 1.1.1.1 9999 | tee response.txt

(I did indeed confirm that running nc -u 1.1.1.1 9999 and typing "request" on a line by itself returns the expected response. But how to capture it?)

Thanks in advance!

Best Answer

When I tried the nc command you used it hung and never exited. So I added the -q 2 option to timeout after 2 seconds and it works for me:

chicks@silver 17:34:54 ~ !548 $ echo "foo" | nc -u 127.0.0.1 7777 -q 2 > /tmp/z
chicks@silver 17:34:59 ~ !549 $ cat /tmp/z
foo

So you just have to pick a timeout you can live with. :)