我正在使用以下代码来设置套接字以检测网络错误:
int socket_keepalive(int s, int ktime, int kinterval, int kprobes) {
int enable = 1;
if(setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(int)) < 0) {
printf("setsockopt SO_KEEPALIVE failed (%s)\n", strerror(errno));
return -1;
}
if(setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, &ktime, sizeof(int) < 0)) {
printf("setsockopt TCP_KEEPIDLE failed\n");
perror("SO_KEEPALIVE: ");
return -1;
}
if(setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, &kinterval, sizeof(int) < 0)) {
printf("setsockopt TCP_KEEPINTVL failed\n");
perror("TCP_KEEPINTVL: ");
return -1;
}
if(setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, &kprobes, sizeof(int) < 0)) {
printf("setsockopt TCP_KEEPCNT failed\n");
perror("TCP_KEEPCNT: ");
return -1;
}
return 0;
}
我这样调用上面的函数:
socket_keepalive(sock, 30, 10, 1);
我希望网络出现错误40秒后,套接字将断开连接。但是,在远程网络出现错误之后,大约需要170秒。
知道我在做什么错吗?