在udp中, 可以用SO_SNDTIMEO和SO_RCVTIMEO来实现发送、接收的超时设置, 下面以SO_RCVTIMEO为例来看看:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int iSock = socket(AF_INET, SOCK_DGRAM, 0);
char szBuf[1024] = {0};
struct timeval tv;
tv.tv_sec = atoi(argv[1]); // 注意防core
tv.tv_usec = 0;
setsockopt(iSock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
int iRet = recvfrom(iSock, szBuf, sizeof(szBuf) - 1, 0, NULL, NULL);
printf("iRet is [%d]\n", iRet);
close(iSock);
return 0;
}
看下:
ubuntu@VM-0-15-ubuntu:~/taoge$ ./a.out 1
iRet is [-1]
ubuntu@VM-0-15-ubuntu:~/taoge$ ./a.out 2
iRet is [-1]
ubuntu@VM-0-15-ubuntu:~/taoge$ ./a.out 3
iRet is [-1]
ubuntu@VM-0-15-ubuntu:~/taoge$ ./a.out
Segmentation fault (core dumped)
ubuntu@VM-0-15-ubuntu:~/taoge$
超时时间分别为1, 2, 3秒, 不多说。