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?

bshacklett
  • 1,378
  • 4
  • 19
  • 37

5 Answers5

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
bshacklett
  • 1,378
  • 4
  • 19
  • 37
9

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

Dániel
  • 91
  • 1
  • 1
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.

womble
  • 95,029
  • 29
  • 173
  • 228
2

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

Kousha
  • 21
  • 1
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.

womble
  • 95,029
  • 29
  • 173
  • 228