Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept socket with timeout

Tags:

c

linux

windows

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!

like image 529
Boris Avatar asked Dec 26 '12 19:12

Boris


People also ask

How do I set socket timeout?

You can make an instance of a socket object and call a gettimeout() method to get the default timeout value and the settimeout() method to set a specific timeout value. This is very useful in developing custom server applications.

How does socket timeout work?

Socket timeouts can occur when attempting to connect to a remote server, or during communication, especially long-lived ones. They can be caused by any connectivity problem on the network, such as: A network partition preventing the two machines from communicating. The remote machine crashing.

Does a timeout close the socket?

When there is a problem with the socket connection, such as the network being unavailable or there being no Internet, the socket will keep trying to connect. A socket timeout stops this connection after a specified amount of time.


1 Answers

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.

like image 60
ryanbwork Avatar answered Oct 03 '22 18:10

ryanbwork