The Computer Oracle

Netcat/socat behavior with piping and UDP?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders

--

Chapters
00:00 Netcat/Socat Behavior With Piping And Udp?
02:57 Answer 1 Score 4
03:15 Accepted Answer Score 27
04:17 Answer 3 Score 3
04:40 Thank you

--

Full question
https://superuser.com/questions/331582/n...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#pipe #udp #netcat #socat

#avk47



ACCEPTED ANSWER

Score 27


Ok, I think at least I got something with socat - namely, the option fork needs to be appended to the server line:

$ socat - udp4-listen:5000,reuseaddr,fork

... and then, in another terminal, we can call echo piping into socat client line multiple times on command line, as it will exit immediately (well, after half a second :)):

$ echo "hello" | socat - udp-sendto:127.0.0.1:5000
$ echo "hello" | socat - udp-sendto:127.0.0.1:5000
$ echo "hello" | socat - udp-sendto:127.0.0.1:5000

... and going back to the first terminal, we can see that the server has successfully shown all three hellos:

$ socat - udp4-listen:5000,reuseaddr,fork
hello
hello
hello
^C

 

Note that even with a fork-ed socat server, the line echo "hello" | nc -u 127.0.0.1 5000 will still 'lock' as if waiting for user input; however, now after Ctrl-C and re-running the command, i.e.

$ echo "hello" | nc -u 127.0.0.1 5000
^C
$ echo "hello" | nc -u 127.0.0.1 5000
^C
$ echo "hello" | nc -u 127.0.0.1 5000
^C

... the fork-ed socat server will show three hellos without the need to be restarted..

 

Seemingly, this openBSD netcat doesn't have a fork option - but I'm not sure if it has one that is corresponding to it..

Anyways, hope this helps someone,
Cheers!




ANSWER 2

Score 4


Your netcat is only reading the output from echo's stdout when you use pipe, it's not "connected" to the keyboard anymore. To get the response you're expecting, you can add your three "hello"'s to a file an run

cat [myfile] | nc -u 127.0.0.1 5000



ANSWER 3

Score 3


If you do an strace of the listening nc, it will show that netcat is waiting for the connection, and once it gets it, will connect to that host and port, ignoring all others. You need to add '-k' to keep going and '-w 0' to timeout each connection after 0 seconds. Socat is a better choice, I think.