setsockopt()函数
1、使用setsockopt()实现超时检测时相比其他两种方式的特点是:
只要调用setsockopt函数一次,函数下发所有阻塞函数均可使用,且永久有效。
阻塞函数在到达设置的时间时,会被系统认定为错误,使阻塞函数返回值小于0;
#include <sys/socket.h>
int setsockopt(int socket, int level, int option_name,
const void *option_value, socklen_t option_len);
功能:设置套接字相关的选项信息
参数:
socket: 文件描述符
level: 对应协议层
SOL_SOCKET 应用层
IPPROTO_TCP TCP层
IPPROTO_IP IP层
option_name:选项的名称
SO_BROADCAST 允许发送广播 int
SO_REUSEADDR 允许重复使用地址 int
SO_SNDBUF 获取发送缓冲器大小
SO_RCVBUF 获取接收缓冲区大小
SO_RCVTIMEO 设置接收超时时间
SO_SNDTIMEO 设置发送超时时间
option_value:对应选项的值
option_len:大小
返回值:
成功:0
失败:-1
SO_RCVTIMEO 设置接收超时时间
+++++++++++++++++++++++++++++++++++++
struct timeval {
int tv_sec; 秒
int tv_usec; 微秒
};
+++++++++++++++++++++++++++++++++++++
//使用setsockopt实现网络超时检测
//setsockopt函数只要调用一次,下方所有的阻塞函数都会使用,并永久有效
struct timeval out_time;
out_time.tv_sec = 5;
out_time.tv_usec = 0;
if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &out_time, sizeof(out_time)) < 0)
{
errlog(“fail to setsockopt”);
}
下面上实例:
#include <stdio.h>
#include <sys/types.h>