带超时时间的sendto和recvfrom(用SO_SNDTIMEO和SO_RCVTIMEO搞起)

972 篇文章 329 订阅
322 篇文章 11 订阅

       在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秒, 不多说。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值