为 UDP 套接字的 recv fcn 设置超时 [英] setting timeout for recv fcn of a UDP socket

查看:32
本文介绍了为 UDP 套接字的 recv fcn 设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过sendto发送一个UDP数据包,然后通过recv收到应答.如果recv没有收到回复,程序收到不进行.但是,udp 数据包可能会丢失,或者由于某种原因,数据包可能无法传递,从而导致程序卡在 recv 行.我想知道如果没有数据包到达,例如一分钟,如何为 recv 设置超时,然后跳过该行并继续执行代码?

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?

我没有粘贴完整的代码,因为它是一个通用的 udp 代码,我的问题与唯一的 recv 有关.最后一点,开发环境是linux.

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);

推荐答案

你可以使用 pollselect 或类似的东西:

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 ...
}

这篇关于为 UDP 套接字的 recv fcn 设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆