2019独角兽企业重金招聘Python工程师标准>>>

TCP之keepalive

In order to understand what TCP keepalive (which we will just call keepalive) does, you need do nothing more than read the name: keep TCP alive. This means that you will be able to check your connected socket (also known as TCP sockets), and determine whether the connection is still up and running or if it has broken.

What is TCP keepalive?

The keepalive concept is very simple: when you set up a TCP connection, you associate a set of timers. Some of these timers deal with the keepalive procedure. When the keepalive timer reaches zero, you send your peer a keepalive probe packet with no data in it and the ACK flag turned on. You can do this because of the TCP/IP specifications, as a sort of duplicate ACK, and the remote endpoint will have no arguments, as TCP is a stream-oriented protocol. On the other hand, you will receive a reply from the remote host (which doesn't need to support keepalive at all, just TCP/IP), with no data and the ACK set.

If you receive a reply to your keepalive probe, you can assert that the connection is still up and running without worrying about the user-level implementation. In fact, TCP permits you to handle a stream, not packets, and so a zero-length data packet is not dangerous for the user program.

This procedure is useful because if the other peers lose their connection (for example by rebooting) you will notice that the connection is broken, even if you don't have traffic on it. If the keepalive probes are not replied to by your peer, you can assert that the connection cannot be considered valid and then take the correct action.

Why use TCP keepalive?

You can live quite happily without keepalive, so if you're reading this, you may be trying to understand if keepalive is a possible solution for your problems. Either that or you've really got nothing more interesting to do instead, and that's okay too. :)

Keepalive is non-invasive, and in most cases, if you're in doubt, you can turn it on without the risk of doing something wrong. But do remember that it generates extra network traffic, which can have an impact on routers and firewalls.

In short, use your brain and be careful.

In the next section we will distinguish between the two target tasks for keepalive:

  • Checking for dead peers
  • Preventing disconnection due to network inactivity

Checking for dead peers

Keepalive can be used to advise you when your peer dies before it is able to notify you. This could happen for several reasons, like kernel panic or a brutal termination of the process handling that peer. Another scenario that illustrates when you need keepalive to detect peer death is when the peer is still alive but the network channel between it and you has gone down. In this scenario, if the network doesn't become operational again, you have the equivalent of peer death. This is one of those situations where normal TCP operations aren't useful to check the connection status.

Think of a simple TCP connection between Peer A and Peer B: there is the initial three-way handshake, with one SYN segment from A to B, the SYN/ACK back from B to A, and the final ACK from A to B. At this time, we're in a stable status: connection is established, and now we would normally wait for someone to send data over the channel. And here comes the problem: unplug the power supply from B and instantaneously it will go down, without sending anything over the network to notify A that the connection is going to be broken. A, from its side, is ready to receive data, and has no idea that B has crashed. Now restore the power supply to B and wait for the system to restart. A and B are now back again, but while A knows about a connection still active with B, B has no idea. The situation resolves itself when A tries to send data to B over the dead connection, and B replies with an RST packet, causing A to finally to close the connection.

Keepalive can tell you when another peer becomes unreachable without the risk of false-positives. In fact, if the problem is in the network between two peers, the keepalive action is to wait some time and then retry, sending the keepalive packet before marking the connection as broken.

    _____                                                     _____|     |                                                   |     ||  A  |                                                   |  B  ||_____|                                                   |_____|^                                                         ^|--->--->--->-------------- SYN -------------->--->--->---||---<---<---<------------ SYN/ACK ------------<---<---<---||--->--->--->-------------- ACK -------------->--->--->---||                                                         ||                                       system crash ---> X||                                     system restart ---> ^|                                                         ||--->--->--->-------------- PSH -------------->--->--->---||---<---<---<-------------- RST --------------<---<---<---||                                                         |

Preventing disconnection due to network inactivity

The other useful goal of keepalive is to prevent inactivity from disconnecting the channel. It's a very common issue, when you are behind a NAT proxy or a firewall, to be disconnected without a reason. This behavior is caused by the connection tracking procedures implemented in proxies and firewalls, which keep track of all connections that pass through them. Because of the physical limits of these machines, they can only keep a finite number of connections in their memory. The most common and logical policy is to keep newest connections and to discard old and inactive connections first.

Returning to Peers A and B, reconnect them. Once the channel is open, wait until an event occurs and then communicate this to the other peer. What if the event verifies after a long period of time? Our connection has its scope, but it's unknown to the proxy. So when we finally send data, the proxy isn't able to correctly handle it, and the connection breaks up.

Because the normal implementation puts the connection at the top of the list when one of its packets arrives and selects the last connection in the queue when it needs to eliminate an entry, periodically sending packets over the network is a good way to always be in a polar position with a minor risk of deletion.

    _____           _____                                     _____|     |         |     |                                   |     ||  A  |         | NAT |                                   |  B  ||_____|         |_____|                                   |_____|^               ^                                         ^|--->--->--->---|----------- SYN ------------->--->--->---||---<---<---<---|--------- SYN/ACK -----------<---<---<---||--->--->--->---|----------- ACK ------------->--->--->---||               |                                         ||               | <--- connection deleted from table      ||               |                                         ||--->- PSH ->---| <--- invalid connection                 ||               |                                         |

Using TCP keepalive under Linux

Linux has built-in support for keepalive. You need to enable TCP/IP networking in order to use it. You also need procfs support and sysctl support to be able to configure the kernel parameters at runtime.

The procedures involving keepalive use three user-driven variables:

tcp_keepalive_time

the interval between the last data packet sent (simple ACKs are not considered data) and the first keepalive probe; after the connection is marked to need keepalive, this counter is not used any further

tcp_keepalive_intvl

the interval between subsequential keepalive probes, regardless of what the connection has exchanged in the meantime

tcp_keepalive_probes

the number of unacknowledged probes to send before considering the connection dead and notifying the application layer

Remember that keepalive support, even if configured in the kernel, is not the default behavior in Linux. Programs must request keepalive control for their sockets using the setsockopt interface. There are relatively few programs implementing keepalive, but you can easily add keepalive support for most of them following the instructions explained later in this document.

Configuring the kernel

There are two ways to configure keepalive parameters inside the kernel via userspace commands:

  • procfs interface
  • sysctl interface

We mainly discuss how this is accomplished on the procfs interface because it's the most used, recommended and the easiest to understand. The sysctl interface, particularly regarding the sysctl(2) syscall and not the sysctl(8) tool, is only here for the purpose of background knowledge.

Making changes persistent to reboot

There are several ways to reconfigure your system every time it boots up. First, remember that every Linux distribution has its own set of init scripts called by init (8). The most common configurations include the /etc/rc.d/ directory, or the alternative, /etc/init.d/. In any case, you can set the parameters in any of the startup scripts, because keepalive rereads the values every time its procedures need them. So if you change the value of tcp_keepalive_intvl when the connection is still up, the kernel will use the new value going forward.

There are three spots where the initialization commands should logically be placed: the first is where your network is configured, the second is the rc.local script, usually included in all distributions, which is known as the place where user configuration setups are done. The third place may already exist in your system. Referring back to the sysctl (8) tool, you can see that the -p switch loads settings from the /etc/sysctl.conf configuration file. In many cases your init script already performs the sysctl -p (you can "grep" it in the configuration directory for confirmation), and so you just have to add the lines in /etc/sysctl.conf to make them load at every boot. For more information about the syntax of sysctl.conf(5), refer to the manpage.

=========END=========

转载于:https://my.oschina.net/xinxingegeya/blog/725935

TCP之keepalive相关推荐

  1. tcp retransmission 出现的原因_浅谈TCP的keepalive机制

    相关背景: hbase集群大量regionserver节点进程挂掉,排查log发现每个节点上的有大量的和datanode建立连接失败的报错信息,进一步排查是大量的Too Many Open Files ...

  2. go tcp客户端自动重连_深入分析TCP的keepalive和time_wait,总能发现新东西

    TCP是一个有状态通讯协议,所谓的有状态是指通信过程中通信的双方各自维护连接的状态. 一.TCP keepalive 先简单回顾一下TCP连接建立和断开的整个过程.(这里主要考虑主流程,关于丢包.拥塞 ...

  3. TCP之keepalive机制的应用场景

    2019独角兽企业重金招聘Python工程师标准>>> 如果TCP连接被对方正常关闭,也就是说,对方是正确地调用了close或者shutdown的话,那么Recv或Send调用就能马 ...

  4. 谈谈Http长连接和Keep-Alive以及Tcp的Keepalive

    一次性说清楚秒验(本机号码一键登录) 2021-03-02 技术总监面试,提问:Redis热点key解决方案 2021-02-28 [性能测试]轻量级压测工具Hey 2021-02-23 我们知道Ht ...

  5. 理解TCP之Keepalive

    理解HTTP之keep-alive 在前面一篇文章中讲了TCP的keepalive,这篇文章再讲讲HTTP层面keep-alive.两种keepalive在拼写上面就是不一样的,只是发音一样,于是乎大 ...

  6. java tcp keepalive_socket keepalive理解

    java socket编程中有个keepalive选项,看到这个选项经常会误解为长连接,不设置则为短连接,实则不然. socket连接建立之后,只要双方均未主动关闭连接,那这个连接就是会一直保持的,就 ...

  7. linux tcp keepalive,Linux下TCP的Keepalive相关参数学习

    一 基本原理 TCP的Keepalive可以简单理解成为keep tcp alive,用来检测TCP sockets的连接是否正常或是已经断开. Keeplived的原理很简单,当建立一个TCP连接时 ...

  8. 关于 HTTP 和 TCP 的 keep-alive

    Connection 头(header) 决定当前的事务完成后,是否会关闭网络连接.如果该值是"keep-alive",网络连接就是持久的,不会关闭,使得对同一个服务器的请求可以继 ...

  9. VC中如何设置Socket的TCP/IP KeepAlive机制(MSDN)

    说明: A TCP keep-alive packet is simply an ACK with the sequence number set to one less than the curre ...

  10. go tcp连接_TCP漫谈之keepalive和time_wait

    TCP是一个有状态通讯协议,所谓的有状态是指通信过程中通信的双方各自维护连接的状态. 一.TCP keepalive 先简单回顾一下TCP连接建立和断开的整个过程.(这里主要考虑主流程,关于丢包.拥塞 ...

最新文章

  1. 《HTML5 canvas开发详解(第2版)》——1.9 HTML5 Canvas对象
  2. IntelliJ IDEA Community 社区版配置 Web 开发环境(Gradle + Tomcat)
  3. linux中yum怎么安装服务器,yum安装(linux如何安装yum)
  4. hpunix下11gRac的安装
  5. 9:23 2009-7-23
  6. python通过什么对象连接数据库_干货!python与MySQL数据库的交互实战
  7. 数据结构上机实践第五周项目2 - 建立链栈算法库
  8. 如何利用shell查看Ubuntu系统版本号和电脑类型
  9. [裴礼文数学分析中的典型问题与方法习题参考解答]5.1.24
  10. Ubuntu下完全删除Edraw软件
  11. USB转串口,JLINK驱动安装(亲测有效)
  12. 人脸识别系统落地酒店 刷脸入住更安全
  13. 安装ubuntu20.04无法连接wifi问题
  14. VS2015专业版打开处于白屏状态
  15. uni-app h5 使用微信JSSDK的方式
  16. Word删除全文图片
  17. 二阶偏微分方程组 龙格库塔法_1、经典四阶龙格库塔法解一阶微分方程组
  18. ​危机——疫情是“危”,5G是“机”
  19. 解决maven pom依赖的jar无法从私服下载问题【复制大法】
  20. Android自定义View——实现水波纹效果类似剩余流量球

热门文章

  1. python写透视挂_python – OpenCV透视变换给出了意想不到的结果
  2. python列表初始化长度_在Python中预先初始化列表内容和长度的实现
  3. abstract class和interface有什么区别?_程序员必须掌握了解的21个Java核心技术,还在等什么?...
  4. rac san+oracle_Oracle RAC安装部署之规划(一)
  5. CS224N刷题——Assignment3.1_A window into NER
  6. PDF文件编辑方法:PDF怎么插入图片背景
  7. Docker 容器使用教程
  8. mysql 5.6的安装
  9. rman备份优化思路
  10. js 简单语法 集合