PDA

View Full Version : 4.4 - How can I listen on more than one port at a time?


Loco
07-26-2002, 11:05 PM
4.4 - How can I listen on more than one port at a time?

The best way to do this is with the select() call. This tells the kernel to let you know when a socket is available for use. You can have one process do i/o with multiple sockets with this call. If you want to wait for a connect on sockets 4, 6 and 10 you might execute the following code snippet:

fd_set socklist;

FD_ZERO(&socklist); /* Always clear the structure first. */
FD_SET(4, &socklist);
FD_SET(6, &socklist);
FD_SET(10, &socklist);
if (select(11, NULL, &socklist, NULL, NULL) < 0)
perror("select");


The kernel will notify us as soon as a file descriptor which is less than 11 (the first parameter to select()), and is a member of our socklist becomes available for writing. See the man page on select() for more details.

From: Chris Niekel

I tested on IRIX 6.5, and the fd_set should NOT be in the writeset, but in the read-set. I.e. select(11, &fds, 0, 0, 0). If you put it in the write-set IRIX 6.5 lets you wait forever.

From: Gavin

How would you do this while using poll()?

From: Zoran

poll(2) expects a pointer to an array of struct pollfd. The second argument shall tell poll how many pollfd's there are. So to achieve the above you do:

int num = 0;
struct pollfd threesockets[] = {
{ 4, POLLIN, 0 },
{ 6, POLLIN, 0 },
{ 10, POLLIN, 0 },
};

if((num = poll(&threesockets[0],
sizeof threesockets / sizeof threesockets[0],
-1)) > 0 ) {
if(threesockets[0].revents) {
/* check with POLLIN whether there
is data to read from port 4,
POLLERR, POLLHUP and POLLNVAL
signal other events */
}
if(threesockets[1].revents) {...}

if(threesockets[2].revents) {...}

} else {
/* an error occured in poll */
}