tcp_keepalive编程

KeepAlive机制中设置的参数包含如下:

  • SO_KEEPALIVE 设置套接字的keepalive状态
  • TCP_KEEPIDLE 关闭一个非活跃连接之前进行探测的最大时长,默认值为2h
  • TCP_KEEINTVL 两次探测的时间间隔,默认值为150s,即每次间隔75s
  • TCP_KEEPCNT 关闭一个非活跃连接之前进行的最大操作次数,默认值为8
    这些默认值位于/proc/sys/net/ipv4目录下。
    程序实现时可以通过setsockopt函数进行相关设置,代码段如下:
//设置socket为TCP_KEEPALIVE
int keepAlive = 1;
setsockopt(listenfd, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepAlive, sizeof(keepAlive));
int keepIdle = 6;
int keepInterval = 5;
int keepCount = 3;
setsockopt(listenfd, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle));
setsockopt(listenfd, SOL_TCP,TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval)); 
setsockopt(listenfd,SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
本站总访问量