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?