13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 608.15. recv(), recvfrom()Recieve data on a socketPro<strong>to</strong>types#include #include ssize_t recv(int s, void *buf, size_t len, int flags);ssize_t recvfrom(int s, void *buf, size_t len, int flags,struct sockaddr *from, socklen_t *fromlen);DescriptionOnce you have a socket up and connected, you can read incoming data from the remoteside using the recv() (for TCP SOCK_STREAM sockets) and recvfrom() (for UDP SOCK_DGRAMsockets).Both functions take the socket descrip<strong>to</strong>r s, a pointer <strong>to</strong> the buffer buf, the size (in bytes) ofthe buffer len, and a set of flags that control how the functions work.Additionally, the recvfrom() takes a struct sockaddr*, from that will tell you where thedata came from, and will fill in fromlen with the size of struct sockaddr. (You must alsoinitialize fromlen <strong>to</strong> be the size of from or struct sockaddr.)So what wonderous flags can you pass in<strong>to</strong> this function? Here are some of them, but youshould check your local man pages for more information and what is actually supported on yoursystem. You bitwise-or these <strong>to</strong>gether, or just set flags <strong>to</strong> 0 if you want it <strong>to</strong> be a regular vanillarecv().MSG_OOBMSG_PEEKMSG_WAITALLRecieve Out of Band data. This is how <strong>to</strong> get data that has beensent <strong>to</strong> you with the MSG_OOB flag in send(). As the recieving side,you will have had signal SIGURG raised telling you there is urgentdata. In your handler for that signal, you could call recv() withthis MSG_OOB flag.If you want <strong>to</strong> call recv() “just for pretend”, you can call itwith this flag. This will tell you what’s waiting in the buffer forwhen you call recv() “for real” (i.e. without the MSG_PEEK flag.It’s like a sneak preview in<strong>to</strong> the next recv() call.Tell recv() <strong>to</strong> not return until all the data you specified in thelen parameter. It will ignore your wishes in extreme circumstances,however, like if a signal interrupts the call or if some error occursor if the remote side closes the connection, etc. Don’t be mad withit.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!