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...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 418.1. accept()Accept an incoming connection on a listening socketPro<strong>to</strong>types#include #include int accept(int s, struct sockaddr *addr, socklen_t *addrlen);DescriptionOnce you’ve gone through the trouble of getting a SOCK_STREAM socket and setting it up forincoming connections with listen(), then you call accept() <strong>to</strong> actually get yourself a newsocket descrip<strong>to</strong>r <strong>to</strong> use for subsequent communication with the newly connected client.The old socket that you are using for listening is still there, and will be used for furtheraccept() calls as they come in.sThe listen()ing socket descrip<strong>to</strong>r.addrThis is filled in with the address of the site that’s connecting <strong>to</strong> you.addrlenThis is filled in with the sizeof() the structure returned in the addrparameter. You can safely ignore it if you assume you’re getting a structsockaddr_in back, which you know you are, because that’s the type youpassed in for addr.accept() will normally block, and you can use select() <strong>to</strong> peek on the listening socketdescrip<strong>to</strong>r ahead of time <strong>to</strong> see if it’s “ready <strong>to</strong> read”. If so, then there’s a new connection waiting<strong>to</strong> be accept()ed! Yay! Alternatively, you could set the O_NONBLOCK flag on the listening socketusing fcntl(), and then it will never block, choosing instead <strong>to</strong> return -1 with errno set <strong>to</strong>EWOULDBLOCK.The socket descrip<strong>to</strong>r returned by accept() is a bona fide socket descrip<strong>to</strong>r, open and connected<strong>to</strong> the remote host. You have <strong>to</strong> close() it when you’re done with it.Return Valueaccept() returns the newly connected socket descrip<strong>to</strong>r, or -1 on error, with errno setappropriately.Exampleint s, s2;struct sockaddr_in myaddr, remoteaddr;socklen_t remoteaddr_len;myaddr.sin_family = AF_INET;myaddr.sin_port = h<strong>to</strong>ns(3490); // clients connect <strong>to</strong> this portmyaddr.sin_addr.s_addr = INADDR_ANY; // au<strong>to</strong>select IP addresss = socket(PF_INET, SOCK_STREAM, 0);bind(s, (struct sockaddr*)myaddr, sizeof(myaddr));

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

Saved successfully!

Ooh no, something went wrong!