windows和linux下启用keepalive并且自定义心跳包时间

windows下启用keepalive并且自定义心跳包时间

  • 前言

前言

最近在编写c的socket,在使用keepalive时候遇到一些问题,如下设置即可


#include  
struct  tcp_keepalive  {
    u_long    onoff;
    u_long    keepalivetime;
    u_long    keepaliveinterval;
};
#define  SIO_RCVALL                  _WSAIOW(IOC_VENDOR,1)
#define  SIO_RCVALL_MCAST            _WSAIOW(IOC_VENDOR,2)
#define  SIO_RCVALL_IGMPMCAST        _WSAIOW(IOC_VENDOR,3)
#define  SIO_KEEPALIVE_VALS          _WSAIOW(IOC_VENDOR,4)
#define  SIO_ABSORB_RTRALERT          _WSAIOW(IOC_VENDOR,5)
#define  SIO_UCAST_IF                _WSAIOW(IOC_VENDOR,6)
#define  SIO_LIMIT_BROADCASTS        _WSAIOW(IOC_VENDOR,7)
#define  SIO_INDEX_BIND              _WSAIOW(IOC_VENDOR,8)
#define  SIO_INDEX_MCASTIF            _WSAIOW(IOC_VENDOR,9)
#define  SIO_INDEX_ADD_MCAST          _WSAIOW(IOC_VENDOR,10)
#define  SIO_INDEX_DEL_MCAST          _WSAIOW(IOC_VENDOR,11)
//上面的结构体和define是#include  的内容
int socket_set_keepalive (int fd)
{
#ifdef WIN32
    struct tcp_keepalive kavars;
    struct tcp_keepalive alive_out;
    kavars.onoff = TRUE;
    kavars.keepalivetime = 30*1000;
    kavars.keepaliveinterval = 6*000;

    /* Set: use keepalive on fd */
    int alive = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *) &alive,sizeof alive) != 0)
    {
        return -1;
    }

    unsigned long ulBytesReturn = 0;
    WSAIoctl(fd, SIO_KEEPALIVE_VALS, &kavars, sizeof(kavars),&alive_out, sizeof(alive_out), &ulBytesReturn, NULL, NULL);
#else
    int keepAlive = 1;    // 非0值,开启keepalive属性
    int keepIdle = 30;    // 如该连接在60秒内没有任何数据往来,则进行此TCP层的探测
    int keepInterval = 5; // 探测发包间隔为5秒
    int keepCount = 3;        // 尝试探测的最多次数

    setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive));
    setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle));
    setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
    setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
#endif
    return 0;
}

windows和linux下启用keepalive并且自定义心跳包时间_第1张图片

你可能感兴趣的:(工具编译开发,编程开发)