The application layer uses the following functions for each socket to enable the keepalive mechanism. The parameters are configured as described above.
Setsockopt (RS, sol_socket, so_keepalive, (void *) & keepalive, sizeof (keepalive ));
Note: keepalive is a TCP protocol package. It is not an application-layer data packet, meaning that the Protocol package cannot be obtained from the application layer through functions such as Recv. You can refer to the packet capture tool.
========================================================== ======================================
1. What is a keepalive timer? [1]
There is no data stream on an idle (idle) TCP connection. Many beginners of TCP/IP are surprised by this. That is to say, if no process at both ends of the TCP connection sends data to the other end, there is no data exchange between the two TCP modules. You may find polling in other network protocols, but it does not exist in TCP. The implication is that we only need to start a client process and establish a TCP connection with the server. No matter how many hours, days, weeks, or months you leave, the connection still exists. The middle router may crash or restart, and the telephone line may go down or back up. As long as the host at both ends of the connection is not restarted, the connection remains established.
This means that no application-level timer is available for applications on both the client and server to detect inactivity ), this causes the termination of any application. However, sometimes the server needs to know whether the client host has crashed and closed, or crashed but restarted. Many implementations provide a survival timer to complete this task.
The survival timer is a controversial feature. Many people think that even if this feature is needed, such round-robin to the other party should also be done by the application, rather than in TCP. In addition, if a connection is temporarily interrupted on an intermediate network between two terminal systems, the survival option can cause the termination of a good connection between two processes. For example, if a middle-end router crashes or restarts to send a survival test, TCP will think that the client host has crashed, but this is not the case.
Keepalive is not part of the TCP specification. The Host Requirements RFC lists three reasons for not using it: (1) during a short fault, they may cause a good connection to be released (dropped ), (2) they consume unnecessary bandwidth, and (3) They (extra) spend money on the Internet where data packets are billed. However, a survival timer is provided in many implementations.
Some server applications may occupy resources on the client. They need to know whether the client host crashes. The survival timer can provide probe services for these applications. Many versions of the Telnet server and rlogin server provide the survival option by default.
PC users use the TCP/IP protocol to log on to a host through Telnet. This is a common example of survival timer. If a user only turns off the power at the end of use and does not log off, then the user leaves a semi-open connection. In Figure 18.16, we can see how to get a reset (reset) returned by sending data on a semi-open connection, but that is the data sent by the client on the client. If the client disappears, the server is left with a semi-open connection, and the server is waiting for the client data, the waiting will continue forever. The survival feature aims to detect this semi-open connection on the server side.
Ii. How does keepalive work? [1]
In this description, we refer to the section that uses the survival option as the server and the other end as the client. You can also set this option on the client, and there is no reason not to allow this, but it is usually set on the server. If both ends of the connection need to detect whether the other end disappears, you can set both ends (such as NFS ).
If no activity is performed within two hours on a given connection, the server sends a detection segment to the client. (We will see the probe section in the following example .) The client host must be in one of the following four States:
1) The client host is still active (UP) and can be reached from the server. From the normal response of the client TCP, the server knows that the other party is still active. The TCP of the server resets the active timer for the next two hours. If the application communication occurs before the expiration of the two hours, the timer resets the timer for the next two hours, and then exchange data.
2) The client has crashed, shut down, or is restarting. In both cases, TCP does not respond. The server does not receive a Detection Response and times out after 75 seconds. The server will send a total of 10 such probes, each of which is 75 seconds. If no response is received, the client host is considered closed and the connection is terminated.
3) The client has crashed but has restarted. In this case, the server will receive a response to its survival detection, but the response is a reset, causing the server to terminate the connection.
4) The client host is active, but the slave server cannot be reached. This is similar to status 2 because TCP cannot distinguish the two. It can only indicate that no response has been received to it.
The server does not have to worry about the client host being shut down and then restarted (this refers to the normal shutdown by the operator, rather than the host crash ). When the system is shut down by the operator, all application processes (that is, client processes) will be terminated, and client TCP will send a fin over the connection. After receiving the fin, the server TCP reports the end of a file to the server process to allow the server to detect this state.
In the first State, the server application does not know whether the survival test has occurred. Everything is handled by the TCP layer, and the survival detection is transparent to the application until the following three States are 2, 3, and 4. In these three states, an error message is returned to the server application through TCP of the server. (Generally, the server sends a read request to the network, waiting for the client data. If the survival feature returns an error message, the message is returned to the server as the return value of the read operation .) In status 2, the error message is similar to "connection timeout ". Status 3 indicates that the connection is reset by the other party ". The fourth state may look like a connection timeout, or other error messages may be returned based on whether the ICMP error message related to the connection is received.
Windows implementation:
In a normal TCP connection, when we call the following Recv or send in an infinite wait mode:
Ret = Recv (S, & Buf [idx], nleft, flags );
Or
Ret = Send (S, & Buf [idx], nleft, flags );
If the TCP connection is normally closed by the other party, that is, if the other party correctly calls closesocket (s) or shutdown (s), the preceding Recv or send call will return immediately, and an error is reported. This is because closesocket (s) or shutdown (s) has a normal shutdown process, which will tell the other party that "the TCP connection has been closed and you do not need to send or accept the message ". However, if the network cable is suddenly unplugged and the machine at any end of the TCP connection suddenly loses power or restarts, at this time, the party that is executing the Recv or send operation will wait because there is no notification of connection interruption, that is, it will be stuck for a long time. The solution to this problem is to start the keepalive mechanism in TCP programming.
struct TCP_KEEPALIVE inKeepAlive = {0}; unsigned long ulInLen = sizeof(struct TCP_KEEPALIVE); struct TCP_KEEPALIVE utKeepAlive = {0}; unsigned long ulOutLen = sizeof(struct TCP_KEEPALIVE); unsigned long ulBytesReturn = 0; inKeepAlive.onoff=1; inKeepAlive.keepaliveinterval=5000; //单位为毫秒 inKeepAlive.keepalivetime=1000; //单位为毫秒 ret=WSAIoctl(s, SIO_KEEPALIVE_VALS, (LPVOID)&inKeepAlive, ulInLen, (LPVOID)&outKeepAlive, ulOutLen, &ulBytesReturn, NULL, NULL);
KeepAliveTime indicates the detection frequency when the TCP connection is in a smooth state. Once the detection packet does not return, it is sent at the keepaliveinterval frequency. After several retries, if no test packet is returned, it is concluded that the TCP connection is disconnected, so the preceding Recv or send call can return immediately without restriction.
Is a description of the above text. Before bright packets are sent, TCP is in a smooth state. keepalive sends a test packet at a frequency of 1000 milliseconds (value of KeepAliveTime). When it is sent to 32nd test packets, no test packet is returned, so we sent the test packet at a frequency of 5000 milliseconds (KeepAliveTime value). After resending the packet several times, the test packet was not returned, so we came to the conclusion that the TCP connection has been disconnected!
For Win2k/XP/2003, you can find the keepalive parameter that affects all connections of the entire system from the following registry key:
[HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ Tcpip \ Parameters]
"KeepAliveTime" = DWORD: 006ddd00 "keepaliveinterval" = DWORD: 000003e8 "maxdataretries" = "5 ″
For a utility, the idle time for two hours is too long. Therefore, we need to manually enable the keepalive function and set reasonable keepalive parameters. In XP and win2003 systems, you can set individual sockets, but inWindows2000. It cannot be set separately. If it is set, all sockets of the entire system will be affected.
Linux implementation:
So_keepalive/tcp_keepcnt/tcp_keepidle/tcp_keepintvl if one party has closed or terminated the connection abnormally, but the other party does not know, we call this TCP connection semi-open. TCP uses keepalive to detect semi-open connections. In highly concurrent network servers, the socket is often missed, and a large number of close_wait connections occur. At this time, you can set the keepalive option to solve this problem. Of course, there are other ways to solve this problem. For details, refer to reference 8.
使用方法如下://Setting For KeepAlive int keepalive = 1; setsockopt(incomingsock,SOL_SOCKET,SO_KEEPALIVE,(void*)(&keepalive),(socklen_t)sizeof(keepalive)); int keepalive_time = 30; setsockopt(incomingsock, IPPROTO_TCP, TCP_KEEPIDLE,(void*)(&keepalive_time),(socklen_t)sizeof(keepalive_time)); int keepalive_intvl = 3; setsockopt(incomingsock, IPPROTO_TCP, TCP_KEEPINTVL,(void*)(&keepalive_intvl),(socklen_t)sizeof(keepalive_intvl));int keepalive_probes= 3; setsockopt(incomingsock, IPPROTO_TCP, TCP_KEEPCNT,(void*)(&keepalive_probes),(socklen_t)sizeof(keepalive_probes));设置SO_KEEPALIVE选项来开启KEEPALIVE,然后通过TCP_KEEPIDLE、TCP_KEEPINTVL和TCP_KEEPCNT设置keepalive的开始时间、间隔、次数等参数。 当然,也可以通过设置/proc/sys/net/ipv4/tcp_keepalive_time、tcp_keepalive_intvl和tcp_keepalive_probes等内核参数来达到目的,但是这样的话,会影响所有的socket,因此建议使用setsockopt设置。
Http://blog.csdn.net/cccallen/article/details/8003324
TCP heartbeat | TCP keepalive ()