I'm trying to capture UDP traffic which is being sent as StatsD metrics (on port 8125).
The most simple approach I tried is to run nc -ul 8125
which prints the metrics to the terminal...but they are not newline separated. Additionally, piping the output to grep doesn't display anything.
The next approach I tried was socat - udp-listen:8125
which gives similar results to netcat.
However, when I pass in the -v flat and pipe stderr to stdout, (socat -v - udp-listen:8125 2> &1 | grep ...
) then I get vaguely decent results but there's lots of additional unwanted output.
I also tried tshark, tshark -l -f "port 8125" -i ln0 -E separator=, -Tfields -e data
but this prints the output as hexadecimal...not ascii. I can pass in the -x flag, which prints both the hex and the ascii side by side. Not really what I want, and not very grep friendly. I've also tried a bunch of other tshark options, but nothing was able to simply print the UDP metrics.
I have seen some examples where somebody doing something similar is pipling output like | while read output; do echo $output; done;
However, I've not had any success with that approach and I'm not really a unix guy so I'm struggling to come up with a solution.
After all, it doesn't seem like such a uncommon task, and nc -ul 8125
is almost there....
To give more context...the code doing the sending looks like this:
var udpClient = new UdpClient();
udpClient.Connect("127.1", 9999);
while (true)
{
var bytes = Encoding.UTF8.GetBytes("hi");
udpClient.Send(bytes, bytes.Length);
Thread.Sleep(1000);
}
the desired output would look like
hi
hi
hi
...
whereas nc -ul 9999
outputs hihihihihi....
This seems to work although there is a bit more than just new line attached. Also maybe this thread can help: https://unix.stackexchange.com/questions/458951/how-can-i-add-message-delimiters-to-a-udp-stream-socat-is-piping
To expand why
sed G
works... sed has two "spaces" pattern space and hold space.sed G
basically takes what's in the pattern space and adds newline to it. In this case the pattern space is empty so it effectively just adds a new line.