<< Prev | Beej's Guide to Network Programming (cloned from beej.us) | Next >> |
Hosted at Teoria dei Segnali.it - Blog - Download - Signal Transmission - Internet Application Layer - Wiki - Newsletter |
Accept an incoming connection on a listening socket
#include <sys/types.h> #include <sys/socket.h> int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
Once you've gone through the trouble of getting a SOCK_STREAM socket and setting it up for incoming connections with listen(), then you call accept() to actually get yourself a new socket descriptor to 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 further accept() calls as they come in.
accept() will normally block, and you can use select() to peek on the listening socket descriptor ahead of time to see if it's "ready to read". If so, then there's a new connection waiting to be accept()ed! Yay! Alternatively, you could set the O_NONBLOCK flag on the listening socket using fcntl(), and then it will never block, choosing instead to return -1 with errno set to EWOULDBLOCK.
The socket descriptor returned by accept() is a bona fide socket descriptor, open and connected to the remote host. You have to close() it when you're done with it.
accept() returns the newly connected socket descriptor, or -1 on error, with errno set appropriately.
int s, s2; struct sockaddr_in myaddr, remoteaddr; socklen_t remoteaddr_len; myaddr.sin_family = AF_INET; myaddr.sin_port = htons(3490); // clients connect to this port myaddr.sin_addr.s_addr = INADDR_ANY; // autoselect IP address s = socket(PF_INET, SOCK_STREAM, 0); bind(s, (struct sockaddr*)myaddr, sizeof(myaddr)); listen(s, 10); // set s up to be a server (listening) socket for(;;) { s2 = accept(s, &remoteaddr, &remoteaddr_len); // now you can send() and recv() with the // connected client via socket s2 }
socket(),
listen(),
<< Prev | Beej's Guide to Network Programming (cloned from beej.us) | Next >> |