2

I'm currently using sockets in a project where I want to set a timeout of 5 seconds in the recv function. I found in this question that setsockopt with SO_RCVTIMEO option, should do this, but the problem is that it also affects the accept() function and I only want a timeout for the recv() function. Here's how I set up the timeout:

/*Setting timeout for bad headers*/                                                                                                                                                                                                  
struct timeval tv;                                                                                                                                                                                                                   
tv.tv_sec = 5; /* 5 seconds timeout for receiving a request */                                                                                                                                                                       
tv.tv_usec= 0;                                                                                                                                                                                                                       
setsockopt(fd, SOL_SOCKET, 
           SO_RCVTIMEO,(struct timeval *)&tv, 
           sizeof(struct timeval));  

The idea is that if a client sends a corrupted header (with an incorrect message length for example), the thread waits at most 5 seconds to drop the request.

So, is it possible to set this timeout only for the recv() function without affecting the accept() function? If so, how do I do it?

Community
  • 1
  • 1
Jcao02
  • 794
  • 8
  • 24

2 Answers2

10

The SO_RCVTIMEO option only affects the file descriptor you set it on — if you set it on a listening socket, it'll make accept() calls on that socket time out; if you set it on a connected socket, it'll make recv() calls on that socket time out. No socket can have both accept() and recv() called on it, so there's no need for a distinction.

0

Yes, SO_RCVTIMEO will solve your problem. But however in this case, you will have to use SO_RCVTIMEO for each socket of each client, if you are working for multiple clients. If you want to avoid this, use select() function and set the timeout on select() call. The select() will return in three case

  1. Return 0, if the timeout expires before anything interesting happens
  2. On error, -1 is returned
  3. Return the number of file descriptors contained in the three returned descriptor sets

So using select(), you don't have to worry how much clients are connecting and after timeout you can start over again.

Yasir Majeed
  • 739
  • 3
  • 12