Catch up on stories from the past week (and beyond) at the Slashdot story archive

 



Forgot your password?
typodupeerror
×
Programming

Journal npsimons's Journal: read() vs recv() vs recvfrom() for UDP sockets

This may be old news to network programming gurus out there, and those dealing with saner programming languages and libraries probably won't have to worry about it, but I figured I'd post it for all those newbs (like me) to hopefully save them some time.

In C, it turns out that read() and recv() don't work on unconnected sockets (at least UDP, in this, my little story). The man pages do say something along the lines of "recv() is normally used on connected sockets", but to me that seems a bit subtle. Sometimes, some of us need a good *WHACK* on the head with a cluestick, and I finally got one when I was perusing the netcat source code to see what they did that made read() work with UDP. Turns out you have to call recvfrom() at least once on a UDP socket before you can call read() or recv() on it and get it work "reliably". I say "reliably" because what took me so long on this was that I figured UDP meant UNRELIABLE datagram protocol, so that's why I wasn't getting all the data. Turns out sending data over loopback shouldn't drop any packets, even when you use UDP.

And just for reference: no, select() accept() and listen() don't seem to work on UDP sockets either. Bummer :(

This discussion has been archived. No new comments can be posted.

read() vs recv() vs recvfrom() for UDP sockets

Comments Filter:

"Ninety percent of baseball is half mental." -- Yogi Berra

Working...