sven
sven

Reputation: 1121

setting timeout for recv fcn of a UDP socket

I send a UDP packet by sendto, then receive the answer by recv.if recv does not receive the reply, the program does not proceed. However, the udp packet might be lost, or for some reason, the packet may not be delivered, so that the program gets stuck on recv line. I wonder how is it possible to set a timeout for recv if nopacket arrives in ,e.g., a minute, then skip that line and proceed the code?

I am not pasting the full code since it is a generic udp code and my question is related to the only recv. For the final note, the development environment is linux.

unsigned long  buf[maxlen];
struct protoent *proto;     //
struct sockaddr_in server_addr;
int s;  // socket
memset( &server_addr, 0, sizeof( server_addr ));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr = inet_addr(hostname);
sendto(s,msg,sizeof(msg),0,(struct sockaddr *)&server_addr,sizeof(server_addr));

recv(s,buf,sizeof(buf),0);

Upvotes: 4

Views: 18858

Answers (3)

shippo7
shippo7

Reputation: 407

How to set timeout for UDP socket in Linux:

#include <sys/time.h>

struct timeval timeout={2,0}; //set timeout for 2 seconds

/* set receive UDP message timeout */

setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(struct timeval));

/* Receive UDP message */
int recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &slen);
if (recvlen >= 0) {
    //Message Received
}
else{
    //Message Receive Timeout or other error
}

Upvotes: 12

user207421
user207421

Reputation: 311031

I wonder how is it possible to set a timeout for recv

Call setsockopt() with the SO_RCVTIMEO option.

Upvotes: 3

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

You can use poll or select or something similar:

struct pollfd fd;
int res;

fd.fd = s;
fd.events = POLLIN;
res = poll(&fd, 1, 1000); // 1000 ms timeout

if (res == 0)
{
    // timeout
}
else if (res == -1)
{
    // error
}
else
{
    // implies (fd.revents & POLLIN) != 0
    recv(s,buf,sizeof(buf),0); // we can read ...
}

Upvotes: 8

Related Questions