欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

keepalive心跳包

程序员文章站 2024-03-22 22:08:40
...
static int setup_ip_heartbeat(int fd)
{
    int ret = -1;
    // open keepalive on fd
    int alive = 1;
    ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &alive, sizeof(alive));
    if(ret < 0) {
        perror("setsockopt:");
        return -1;
    }

    // 60s no socket data, send heartbeat package
    int idle = 60;
    ret = setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
    if(ret < 0) {
        perror("setsockopt:");
        return -1;
    }

    // if without any respond, 30s later resend package
    int intv = 3;
    ret = setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &intv, sizeof(intv));
    if(ret < 0) {
        perror("setsockopt:");
        return -1;
    }
    
    //try to send 3 times, without any response,mean connect lose
    int cnt = 1;
    ret = setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt));
    if(ret < 0) {
        perror("setsocket:");
        return -1;
    }

}

#include <netinet/tcp.h>
#include <sys/socket.h>

相关标签: 网络编程