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
- 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> 568.12. listen()Tell a socket <strong>to</strong> listen for incoming connectionsPro<strong>to</strong>types#include int listen(int s, int backlog);DescriptionYou can take your socket descrip<strong>to</strong>r (made with the socket() system call) and tell it <strong>to</strong> listenfor incoming connections. This is what differentiates the servers from the clients, guys.The backlog parameter can mean a couple different things depending on the system you on,but loosely it is how many pending connections you can have before the kernel starts rejectingnew ones. So as the new connections come in, you should be quick <strong>to</strong> accept() them so that thebacklog doesn’t fill. Try setting it <strong>to</strong> 10 or so, and if your clients start getting “Connection refused”under heavy load, set it higher.Before calling listen(), your server should call bind() <strong>to</strong> attach itself <strong>to</strong> a specific portnumber. That port number (on the server’s IP address) will be the one that clients connect <strong>to</strong>.Return ValueReturns zero on success, or -1 on error (and errno will be set accordingly.)Exampleint s;struct sockaddr_in myaddr;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));listen(s, 10); // set s up <strong>to</strong> be a server (listening) socket// then have an accept() loop down here somewhereSee Alsoaccept(), bind(), socket()