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:

cpp 复制代码
#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.因为上述代码中,我们设置的TCP_KEEPIDLE=10

相关推荐
茶杯梦轩2 小时前
从零起步学习RabbitMQ || 第二章:RabbitMQ 深入理解概念 Producer、Consumer、Exchange、Queue 与企业实战案例
服务器·后端·消息队列
blasit2 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
YuMiao2 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Sinclair5 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
Rockbean6 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
茶杯梦轩6 天前
CompletableFuture 在 项目实战 中 创建异步任务 的核心优势及使用场景
服务器·后端·面试
海天鹰7 天前
【免费】PHP主机=域名+解析+主机
服务器
DianSan_ERP7 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅7 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
不是二师兄的八戒7 天前
Linux服务器挂载OSS存储的完整实践指南
linux·运维·服务器