Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...