17

I'm trying to send a small string to statsd via nc inside of a read block:

while read line; do
    printf "folder.counter:value|1c" | nc -q 0 -u $host $port
done

Unfortunately, when in UDP mode, nc seems to want to wait indefinitely, even though I've specified -q 0, which the man page says will make the program exit immediately after EOF.

I've tried passing -w 1, but if the data I'm sending comes in at more than one line per second, the data buffers up, and I lose my real time stats (not to mention risking a buffer overflow of some sort).

Is it possible to do what I'm trying to do with netcat, or am I going to need to write something in language which has a statsd library?

2
  • although it didn't solve yours, adding -q 0 solved my issue
    – Colin
    Apr 2, 2016 at 16:49
  • This happens in TCP mode now, which is what brought me here.
    – baitisj
    Aug 25, 2016 at 22:25

5 Answers 5

9

I ended up fixing the problem by switching to socat:

while read line; do
    printf "folder.counter:value|1c" | socat -t 0 - UDP:$host:$port
done
2
  • As there's been no other input, and this resolved my problem, I'm marking it as the answer.
    – bshacklett
    Apr 15, 2013 at 13:05
  • You could have added a 1 second timeout to netcat (adding the arguments -w 1 would have probably worked).
    – parkamark
    Feb 28, 2017 at 14:00
9

You can specify 0 as a timeout value to -w, so it won't wait at all.

3
  • This should be the accepted answer.
    – Petrus K.
    Jan 13, 2017 at 14:49
  • 6
    Zero timeout is unacceptable, the error: invalid wait-time 0
    – AstraSerg
    Sep 26, 2017 at 13:20
  • @Astraserg no it is not, depending on what netcat/NC you have. Works in BSD nc.
    – cde
    Feb 3, 2020 at 21:52
3

I had same issue; solved it using the -c option:

-c, --close                close connection on EOF from stdin

so something like

while read line; do
    printf "folder.counter:value|1c" | nc -cu $host $port
done

Yeah, does not really make sense to "close" a udp-connection - but that ended up working.

2
  • Adding -c solved my problem with netcat (The GNU Netcat) 0.7.1 Sep 15, 2018 at 20:09
  • Fixed my issue on MacOS.
    – spoulson
    Mar 4, 2021 at 21:02
2

adding -v option solved my issue. The reason I am not sure.

0

For us, it was that we were sending an nc payload from one machine to another via a python script. In the python, when we explicitly encoded the payload in 'UTF-8', it just worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.