views:

147

answers:

2

Hi

I am trying to create a reliable service on top of UDP. Here i need to timeout receiveFrom function of window c++ if not packet arrives in specified time. In java i do this DatagramSocket.setSoTimeout but i dont know how to achieve this in windows c++.

thanks

+2  A: 

Take a look at setsockopt() specifically SO_RCVTIMEO.

Len Holgate
+1  A: 

Try using select. This will work on both TCP and UDP sockets. Just another way to do the same thing as in Len's answer, but instead of setting a timeout for all recv operations on the socket you can set the length of the timeout on a call by call basis.

 #include <errno.h>
 #include <stdio.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/time.h>

 int
 input_timeout (int filedes, unsigned int seconds)
 {
   fd_set set;
   struct timeval timeout;

   /* Initialize the file descriptor set. */
   FD_ZERO (&set);
   FD_SET (filedes, &set);

   /* Initialize the timeout data structure. */
   timeout.tv_sec = seconds;
   timeout.tv_usec = 0;

   /* select returns 0 if timeout, 1 if input available, -1 if error. */
   return TEMP_FAILURE_RETRY (select (FD_SETSIZE,
                                      &set, NULL, NULL,
                                      &timeout));
 }

 int
 main (void)
 {
   fprintf (stderr, "select returned %d.\n",
            input_timeout (STDIN_FILENO, 5));
   return 0;
 }
Robert S. Barnes