UNIX network programming-socket keep-alive)

Source: Internet
Author: User

Part 1

[Requirement] checks whether the client program is forcibly terminated without affecting server processing.

[Status quo] The keepalive attribute is set for both the server and client socket. The server sets parameters such as the number of probes. The client and server only enable the keepalive function server to start a monitoring thread and use select to check whether the socket is disabled.

Below is my superficial understanding.

1. About keep alive

Keepalive has three parameters, regardless of windows or Linux:

 

SK-> keepalive_probes: Number of probes SK-> keepalive_time time-out SK-> keepalive_intvl detection Interval

 

For a TCP connection that has been established. If no packets are transmitted between the two parties within the keepalive_time period, the end of the keepalive feature will send the keepalive packet. If no response is received, the packet will be sent at intervals of keepalive_intvl, send keepalive_probes times.If no response is received, the RST packet is sent to close the connection. If a response is received, the timer is cleared.For example★:

 

sk->keepalive_probes = 3;sk->keepalive_time   = 30;sk->keepalive_intvl = 1;

 

The idea is that for TCP connections, keepalive will not be triggered if there is data exchange on the socket for a long time, but if there is no data exchange for 30 seconds, keep alive starts to work: Send the test package, if a response is received, the network is considered as a good one, and the detection is completed. If no response is received, the detection packet is sent every second, three times in total, and no response is returned after three times, then, the RST packet is sent to close the connection, that is, from the network to your socket, you can realize that the network is abnormal, which takes up to 33 seconds.However, if you do not set the keep alive, you may receive the Recv on your socket (Obstruction) until the peer closes the connection, because the Recv does not know that the socket is disconnected.Sending: depending on the size of the data volume, as long as the buffer of the underlying protocol stack can put down your sending data, application-level sending will always be successful. Until the buffer is full, or even the buffer is full, it will block a period of time and try to wait for the buffer to be idle. Therefore, your check on the return value of the send operation fails.With the keep alive function enabled, you can know whether the network is abnormal by directly sending and receiving the function return value.Setting Method (Application Layer ):

 

Int keepalive = 1; // enable the keepalive attribute int keepidle = 60; // if there is no data exchange between the connection within 60 seconds, the int keepinterval = 5 is detected; // The packet sending time interval is 5 seconds int keepcount = 3; // The number of probe attempts. If the response is received for 1st times, the next two times will not be sent again. Setsockopt (RS, sol_socket, so_keepalive, (void *) & keepalive, sizeof (keepalive); setsockopt (RS, sol_tcp, tcp_keepidle, (void *) & keepidle, sizeof (keepidle); setsockopt (RS, sol_tcp, tcp_keepintvl, (void *) & keepinterval, sizeof (keepinterval); setsockopt (RS, sol_tcp, tcp_keepcnt, (void *) & keepcount, sizeof (keepcount ));

 

2. Relationship between select and keep alive

Select is designed for a single process to use multiple sockets and has nothing to do with the detection connection. If only one socket is detected, it is not necessary to use select. When the keepalive function is enabled, the system checks the return value every time it calls Recv or send to determine whether an error occurs or whether it is 0. If an error occurs, check errno for information and check which or which of the following error numbers indicate that the link is broken or does not exist.

In addition,Enable keep alive if you want to regularly check the connection status..The other end cannot afford it, but passively responds to the detection package,This kind of response is the basic requirement of TCP protocol and has nothing to do with keep alive. You do not need to enable keep alive on both the client and server.

 

3. Test Results

Example★Enable the keep alive value on one end of the socket, and then block in a Recv or do not stop sending. In this case, unplug the network cable and test the time from unplugging the network cable to Recv/send.

Test in Linux kernel shows that for a blocked socket, if keep alive is not set during Recv, The Recv will not be returned for a long time even if the network cable is unplugged or ifdown, up to 17 minutes, although this time is much shorter than the default Linux timeout time.However, if keep alive is set, an error is basically returned within keepalive_time + keepalive_probes * keepalive_intvl = 33 seconds.

However, for a socket that is repeatedly sent, after the network cable is unplugged, it will continue sending for a period of time and return success (0 ~ About 10 seconds, depending on the amount of data sent), and then the send blocking, because the protocol layer buffer is full, waiting for the buffer to be idle, about 90 seconds later will return an error. From this point of view, keep alive does not seem to play a role during sending, and the reason is still unclear. Later, it was solved by setting timer before sending.

 

Part 2

We know that when a TCP connection is closed, one of the two ends of the connection needs to be closed. If one side suddenly loses power, the other end cannot be known. Keep_alive of TCP is a mechanism used to detect exceptions.

 

There are three parameters:

 

  • Interval at which heartbeat messages are sent
  • Retry Interval when no response is received
  • Number of Retries
For a Linux operating system, the three values are
[email protected]:~$ cat /proc/sys/net/ipv4/tcp_keepalive_time7200[email protected]:~$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl75[email protected]:~$ cat /proc/sys/net/ipv4/tcp_keepalive_probes9


This means that the keepalive message is initiated every 7200 S (two hours). If no response is received, retry the message in 75 seconds. A maximum of nine retries are considered to be closed.

These three options correspond to the option values of tcp_keepidle, tcp_keepintl, and tcp_keepcnt respectively, and are set through setsockopt.

 

However, the keepalive of TCP has the following BUG:

Normally, the other end of the connection actively calls colse to close the connection. TCP will notify you that the connection has been closed.However, if the other end of the TCP connection suddenly loses connection or the power is down after restart, we do not know that the network has been closed. At this time, if data fails to be sent, TCP will automatically re-transmit the data.. The priority of the retransmission package is higher than keepalive, which means that our keepalive cannot always be sent out. At this time, we do not know that the connection has been interrupted due to an error. After a long retransmission failure, we will know.

 

To avoid this situation, we need to control it on the upper layer of TCP. For this message, record the sending time and the time when the response was received. If no response is received for a long time, the network may be interrupted. If the connection is not sent for a long time, that is, if the communication is not performed for a long time, you can send a packet for keepalive to maintain the existence of the connection.

 

Http://blog.csdn.net/ctthuangcheng/article/details/8596818

 

 

UNIX network programming-socket keep-alive)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.