3

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!

user1011471
  • 179
  • 1
  • 8

1 Answers1

0

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. :)

chicks
  • 3,793
  • 10
  • 27
  • 36
  • It seems like -q is not an option on my nc (Version 6.45 http://nmap.org/ncat). There are idle and wait timeouts but they didn't seem to change the result for me. – user1011471 Dec 12 '14 at 21:19
  • It is included in the `netcat-openbsd` package version `1.105-7ubuntu` on Ubuntu 14.04.1 LTS. I tried the `nc-1.84-22.el6.x86_64` rpm in Centos 6.6, but it does not have the `-q` option. Maybe `socat` will work better for you. – chicks Dec 12 '14 at 23:08