What is TCP Keepalive
Before going into details of TCP keep alive. We will have an overview of what is keepalive in general? Connection-oriented network protocols use the keepalive technique, to check the health of a connection. Keepalive requires a periodic check over a connection when there is no data in either direction for a long time. Very useful in the clearing of dead connections on a server. For example, if there is a server, which accepts connections from all over the world. The server is running on a Linux operating system and has no keepalive mechanism. The server may accept a fixed number of connections from clients(may be huge, but still limited). If clients keep connected for a long time, with no purpose. This may stop the server to accept new connections as the maximum number of clients already connected. Finally will lead to denial of service.
Keepalive In TCP:
TCP is a reliable connection-oriented protocol. TCP keepalive is an optional functionality in TCP, which provides auditing of a connection when a connection is idle (no communication) for a long time. Duration for idle time is configurable. Keepalive procedure is applied to each connection, individually. Once connection idle time exceeds over a configured value, the TCP initiates a keepalive probe.
TCP keepalive probe starts with sending a TCP ack segment to the remote end. The ack segment has sequence number one less than from the current sequence number. If the receiver has an active connection, then ACK is returned to the sender and the probe stops.
When the receiver host is not reachable or TCP not running on the destination port, there will be no response for a keepalive probe, the sender keeps repeating the probe after an interval (default value). After a fixed number of tries, the connection is marked as down. TCP clears the connection resources and indicates to the user for connection close.
Setting TCP keepalive :
As said, Keepalive is optional functionality. To enable a keepalive, the underlying operating system and the TCP user program has to enable TCP keepalive. This section covers enabling keepalive example over CentOs7 Linux and in a c program over the same.
Linux configuration for keep alive:
By default option is enabled in the Linux kernel. Lest check what default values, we have for keepalive using the Sysctl Linux command.
[root@CentOs7- ~]# sysctl -a | grep tcp_keepalive net.ipv4.tcp_keepalive_intvl = 75 net.ipv4.tcp_keepalive_probes = 9 net.ipv4.tcp_keepalive_time = 7200
Linux Sysctl command output has three parameters for keepalive. Let’s try to understand each parameter.
tcp_keepalive_time, the parameter represents the value in seconds for idle time of a connection, before starting TCP keep alive probe.
tcp_keepalive_intvl, have value in seconds. The time interval between consecutive keepalive probes.
tcp_keepalive_probes, an integer value. Represents the number of retries, after which TCP marks the connection dead.