A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2002-07-26 11:05 PM

From: Colombia
Registered: 2002-06-12
Posts: 353

Re: 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)

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, 
        signal other events */ 
  if(threesockets[1].revents) {...} 

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

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


Board footer

Powered by FluxBB