Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exiting the recv loop after a fixed timeout

Tags:

c

sockets

recv

I am using recv to receive a message on the socket from the server.

size_t b_received = 0;
char headers[2048];
while ((b_received = recv(socket_fd,
                              &headers[pos],
                              sizeof(headers) - pos - 1, 0)) > 0) {
    pos += b_received;
}

Sometimes, the server takes too long to send a message and my program is stuck and waiting for the next message.

Is there a way I could just end this loop if the server does not send me the next message after 5 seconds?

like image 309
Amanda Avatar asked Mar 01 '26 10:03

Amanda


1 Answers

You can use the setsockopt function to set a timeout on receive operations:

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Try this to stop the socket :

#include <sys/socket.h>

int shutdown(int socket, int how);

More information here

like image 54
Julien Jm Avatar answered Mar 04 '26 02:03

Julien Jm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!