本文主要是介绍Ubuntu20下C/C++编程开启TCP KeepAlive,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、在linux下,测试tcp保活,可以使用tcp自带keepalive功能。
2、几个重要参数:
-
tcp_keepalive_time:对端在指定时间内没有数据传输,则向对端发送一个keepalive packet,单位:秒
-
tcp_keepalive_intvl:向对端发送了一个keepalive packet,如果对端无响应,则等待tcp_keepalive_intvl秒后再次发送一个keepalive packet
-
tcp_keepalive_probes:向对端发送一个keepalive packet,如果对端没有响应,重发的次数,如果tcp_keepalive_probes次数后,对端都可以响应,则表示这个socket已经断开,本地可以可以关闭这个socket上连接。
3、修改三个参数的系统默认值
上述三个参数当前配置可以在 /proc/sys/net/ipv4查看
可以使用cat查看具体配置,比如
- 全局设置:可更改/etc/sysctl.conf,加上:
sudo vim /etc/sysctl.conf
net.ipv4.tcp_keepalive_intvl = 20
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_time = 60
保存:wq
重启系统:sudo reboot
4、编程设置keeepalive:
#include <netinet/tcp.h>/*开始设置保活机制*/int val = 1;if (setsockopt(nc->sock, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof val) != 0)
{perror("Set SO_KEEPALIVE fail");}/* Default settings are more or less garbage, with the keepalive time* set to 7200 by default on Linux. Modify settings to make the feature* actually useful. *//* Send first probe after interval. */val = 10;if (setsockopt(nc->sock, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0)
{perror("Set TCP_KEEPIDLE fail");}/* Send next probes after the specified interval. Note that we set the* delay as interval / 3, as we send three probes before detecting* an error (see the next setsockopt call). */val = 3;if (setsockopt(nc->sock, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0)
{perror("Set TCP_KEEPINTVL fail");}/* Consider the socket in error state after three we send three ACK* probes without getting a reply. */val = 3;if (setsockopt(nc->sock, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0)
{perror("Set TCP_KEEPCNT fail");}
5、查看通讯情况,打开wireshark,在过滤器输入设置keepalive的Ip格式为:ip.addr==xxx.xxx.xxx.xxx
上图可以看到,每个10秒钟发送了一个keepalive packet.发送Ack=1,对端+1后返回Ack=2
这篇关于Ubuntu20下C/C++编程开启TCP KeepAlive的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!