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> 61When you call recv(), it will block until there is some data <strong>to</strong> read. If you want <strong>to</strong> not block,set the socket <strong>to</strong> non-blocking or check with select() or poll() <strong>to</strong> see if there is incoming databefore calling recv() or recvfrom().Return ValueReturns the number of bytes actually recieved (which might be less than you requested in thelen paramter), or -1 on error (and errno will be set accordingly.)If the remote side has closed the connection, recv() will return 0. This is the normal methodfor determining if the remote side has closed the connection. Normality is good, rebel!Exampleint s1, s2;int byte_count, fromlen;struct sockaddr_in addr;char buf[512];// show example with a TCP stream socket firsts1 = socket(PF_INET, SOCK_STREAM, 0);// info about the serveraddr.sin_family = AF_INET;addr.sin_port = h<strong>to</strong>ns(3490);inet_a<strong>to</strong>n("10.9.8.7", &addr.sin_addr);connect(s1, &addr, sizeof(addr)); // connect <strong>to</strong> server// all right! now that we’re connected, we can recieve some data!byte_count = recv(s1, buf, sizeof(buf), 0);printf("recv()’d %d bytes of data in buf\n", byte_count);// now demo for UDP datagram sockets:s2 = socket(PF_INET, SOCK_DGRAM, 0);fromlen = sizeof(addr);byte_count = recvfrom(s2, buf, sizeof(buf), 0, &addr, &fromlen);printf("recv()’d %d bytes of data in buf\n", byte_count);printf("from IP address %s\n", inet_n<strong>to</strong>a(addr.sin_addr));See Alsosend(), send<strong>to</strong>(), select(), poll(), Blocking

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

Saved successfully!

Ooh no, something went wrong!