UDP 套接字设置超时 [英] UDP Socket Set Timeout
问题描述
我正在尝试在 UDP 套接字上设置 100 毫秒超时.我正在使用 C.我在下面发布了我的代码的相关部分.我不确定为什么这不是超时,而是在它没有收到一个段时挂起.这是否仅适用于未使用 bind() 方法绑定的套接字?
I am trying to set a 100ms timeout on a UDP Socket. I am using C. I have posted relavent pieces of my code below. I am not sure why this is not timing out, but just hangs when it doesn't receive a segment. Does this only work on sockets that are not bound using the bind() method?
#define TIMEOUT_MS 100 /* Seconds between retransmits */
if ((rcv_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");
if ((rcv_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");
//set timer for recv_socket
static int timeout = TIMEOUT_MS;
setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,(char*)&timeout,sizeof(timeout));
if(recvfrom(rcv_sock, ackBuffer,sizeof(ackBuffer), 0,
(struct sockaddr *) &servAddr2, &fromSize) < 0){
//timeout reached
printf("Timout reached. Resending segment %d
", seq_num);
num_timeouts++;
}
推荐答案
SO_RCVTIMEO
选项需要 sys/time.h
中定义的 struct timeval
代码>,而不是像您传递给它的整数.timeval struct
具有用于秒的字段和用于微秒的字段.要将超时设置为 100 毫秒,以下应该可以解决问题:
The SO_RCVTIMEO
option expects a struct timeval
defined in sys/time.h
, not an integer like you're passing to it. The timeval struct
has as field for seconds and a field for microseconds. To set the timeout to 100ms, the following should do the trick:
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100000;
if (setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {
perror("Error");
}
这篇关于UDP 套接字设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!