简体   繁体   中英

How to accept socket with timeout

Is there is a timeout crossplatform soulution to accept client using accept function without setting socket to non-blocking?

I know that i should use select function to it, but what i'm doing wrong?

SOCKET NativesAcceptClient(SOCKET s, int timeout)
{
   int iResult;
   struct timeval tv;
   fd_set rfds;
   FD_ZERO(&rfds);
   FD_SET(s, &rfds);

   tv.tv_sec = (long)timeout;
   tv.tv_usec = 0;

   iResult = select(s, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
   if(iResult > 0)
   {
      return accept(s, NULL, NULL);
   }
   else
   {
     //always here, even if i connect from another application
   }
   return 0;
}

How to fix that? Thanks!

The first parameter of the select call should be equal to the the highest number file descriptor in your fd_set set plus 1 (see here ). Try changing the first argument to s+1 ; you will need to add some logic when your have more than one socket in your set.

The first argument of select() is an int that is at least 1 greater than the highest value of the file descriptors in any of the bitsets. In this case

iResult = select(s + 1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);

should work.

select() returns >0 if a socket is signaled, 0 on timeout, and -1 on error. What value is select() actually returning to you? You are only checking for >0 and <=0, which means you are not differentiating between -1 and 0. If it is returning 0 then no client is connecting to your socket, but if it is returning -1 then your socket is likely not valid to begin with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM