0

我正在使用此代码设置套接字以检测网络错误:

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 秒。

知道我做错了什么吗?

4

0 回答 0