TCP connection Detection keepalive and heartbeat packs

Source: Internet
Author: User
Tags requires socket time interval linux

Using the TCP/C mode software, the connection between the two sides in the connection idle state, if either side of the accidental crash, when the machine, network cable disconnect or router failure, the other side can not know that the TCP connection has been invalidated, unless continue to send data on this connection caused error return. Most of the time, this is not what we need. We want both the server side and the client to detect the connection failures in a timely and efficient manner, and then gracefully complete some cleanup and report the error to the user.

How to detect the abnormal disconnection of one side in time and effectively, there are two kinds of technology can be used. One is the keepalive implemented by the TCP protocol layer and the other is the heartbeat packet implemented by the application layer itself.

TCP does not turn on the KeepAlive function by default because the KeepAlive feature requires additional bandwidth and traffic, which, while insignificant, increases costs in the context of flowmeter charges, on the other hand, A healthy TCP connection may be disconnected due to transient network fluctuations when the keepalive setting is unreasonable. Also, the default keepalive timeout requires 7,200,000 milliseconds, which is 2 hours, and the number of probes is 5 times.

For win2k/xp/2003, you can find keepalive parameters that affect all connections across your system from the following registry key:

[Hkey_local_machine/system/currentcontrolset/services/tcpip/parameters]

"KeepAliveTime" =dword:006ddd00

"KeepAliveInterval" =dword:000003e8

"MaxDataRetries" = "5"

For a practical program, 2 hours of idle time is too long. Therefore, we need to manually open the KeepAlive function and set reasonable keepalive parameters.

Open KeepAlive

BOOL bkeepalive = TRUE;

int nret =:: setsockopt (Socket_handle, Sol_socket, So_keepalive, (char*) &bkeepalive, sizeof (bkeepalive));

if (nret = = socket_error)

{

return FALSE;

}

Set KeepAlive parameters

Tcp_keepalive alive_in = {0};

Tcp_keepalive alive_out = {0};

Alive_in.keepalivetime = 5000; TCP air closure time before first keepalive probes

Alive_in.keepaliveinterval = 1000; Time interval between two times of keepalive probes

Alive_in.onoff = TRUE;

unsigned long ulbytesreturn = 0;

Nret = WSAIoctl (Socket_handle, sio_keepalive_vals, &alive_in, sizeof (alive_in),

&alive_out, sizeof (alive_out), &ulbytesreturn, NULL, NULL);

if (nret = = socket_error)

{

return FALSE;

}

After the KeepAlive option is turned on, for server-side programs that use the IOCP model, once a disconnect is detected, the GetQueuedCompletionStatus function returns false immediately, allowing the server side to purge the connection in time and release the connection-related resources. For clients using the Select model, when a connection disconnect is detected, a select method that blocks on the socket with recv intent will immediately return to Socket_error, knowing that the connection is invalidated, and that the client program has the opportunity to perform cleanup work in a timely manner, alerting the user, or reconnecting. More Wonderful content: http://www.bianceng.cn/Programming/cplus/

Another technique, where the application sends its own heartbeat pack to detect the health of the connection. The client can periodically send a dapper packet to the outgoing server in a timer or low-level thread and wait for the server to respond. The client program does not receive a server response within a certain period of time that the connection is not available, similarly, the server in a certain period of time did not receive the client's heartbeat packet is that the client has dropped the line.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

"Abnormal disconnection" under Windows refers to the reason that TCP connections are not broken gracefully, such as physical links such as network cable failures, and sudden host outages.

There are two ways to detect:

1.TCP connecting both sides timed handshake message

2. Using the KeepAlive detection in the TCP protocol stack

The second method is simple and reliable, with only two sockets of TCP connection set keepalive detection,

So this article only talks about the implementation of the second method under linux,window2000 (no further testing on other platforms)

Windows 2000 platform Bottom file

#include <mstcpip.h>

Defining structures and macros

/*

struct Tcp_keepalive {

U_longonoff;

U_longkeepalivetime;

U_longkeepaliveinterval;

} ;

*/

Tcp_keepalive live,liveout;

live.keepaliveinterval=5000; Send a probe message every 5 seconds, send 5 times without a response, disconnect

live.keepalivetime=30000;//more than 30s without data, send the control packet

Live.onoff=true;

int Opt = 1;

int iRet = setsockopt (accept,sol_socket,so_keepalive, (char *) &opt,sizeof (int));

if (IRet = = 0) {

DWORD DW;

if (:: WSAIoctl (Accept,sio_keepalive_vals,

&live,sizeof (Live), &liveout,sizeof (Liveout),

&dw,null,null) = = Socket_error) {

}

}

Ace under Code

by Rainfish blog.csdn.net/bat603

int Opt = 1;

In the test process, the number of detection detected is 5 times, that is, the following settings, from the most recent message start calculated 10 seconds after each interval of 5 seconds, continuously sent 5 times, that is 35 seconds to find the network is broken

Tcp_keepalive live,liveout;

live.keepaliveinterval=5000; Interval per detection (in milliseconds)

live.keepalivetime=10000; The first time to start sending (in milliseconds)

Live.onoff=true;

int iRet = stream.set_option (sol_socket,so_keepalive,&opt,sizeof (int));

if (IRet = = 0) {

DWORD DW;

This shows a way to get the socket under ACE, that is, the handle (socket) is the handle

if (WSAIoctl (SOCKET) h,sio_keepalive_vals,&live,sizeof (live),

&liveout,sizeof (liveout), &dw,null,null) = = Socket_error) {

Delete Client

Return

}

}

Under Linux Platform

#include "/usr/include/linux/tcp.h" #include "/usr/include/linux/socket.h"////keepalive Implementation, Unit SEC/The following code requires ACE, If you do not include aces, change the use of the ACE function to Linux for the corresponding interface int keepAlive = 1;//set keepAlive int keepidle = 5;//start the TCP empty time before the first keepAlive probe int Keepinterval = 5;//Two keepalive probes interval int keepcount = 3;//Determine the number of keepalive probes before disconnecting if (setsockopt KEEPALIVE, (void*) &keepalive,sizeof (KEEPALIVE)) = = 1) {Ace_debug (Lm_info, Ace_text ("(%p|%t) setsockopt So_
KEEPALIVE error!/n "));  } if (SetSockOpt (S,sol_tcp,tcp_keepidle, (void *) &keepidle,sizeof (keepidle)) = = 1) {Ace_debug (Lm_info, ACE_TEXT
("(%p|%t) setsockopt tcp_keepidle error!/n"))); 
} if (SetSockOpt (S,SOL_TCP,TCP_KEEPINTVL, (void *) &keepinterval,sizeof (keepinterval)) = = 1) {Ace_debug (LM_INFO,
Ace_text ("(%p|%t) setsockopt TCP_KEEPINTVL error!/n")); } if (SetSockOpt (s,sol_tcp,tcp_keepcnt, (void *) &keepcount,sizeof (keepcount)) = = 1) {Ace_debug (Lm_info, ACE_TEX
T ("(%p|%t) setsockopt tcp_keepcnt error!/n"))); }

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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.