内核提供诸如“tcp_keepalive_time”、“tcp_keepalive_intvl”、“tcp_keepalive_probes”等设置。。。这些探针能自动工作吗?或者我必须在我的代码中做些什么才能真正激活?

最佳答案

您需要在套接字上启用这些值。例如在C中:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

void set_tcp_keepalive (int fd)
{
    int val;

    val = 1;
    if (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof (val)) == -1) {
        perror ("setsockopt(SO_KEEPALIVE)");
    }

    val = 60;
    if (setsockopt (fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof (val)) == -1) {
        perror ("setsockopt(TCP_KEEPIDLE)");
    }

    val = 30;
    if (setsockopt (fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof (val)) == -1) {
        perror ("setsockopt(TCP_KEEPINTVL)");
    }

    val = 2;
    if (setsockopt (fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof (val)) == -1) {
        perror ("setsockopt(TCP_KEEPCNT)");
    }
}

关于linux - 内核keepalive是否自动触发?还是我必须从代​​码中触发它们?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54550414/

10-17 01:01