怎樣及時檢測出非正常斷開的TCP串連(zz)

來源:互聯網
上載者:User

作者:在水一魚(powercc@21cn.com)

此處的”非正常斷開”指TCP串連不是以優雅的方式斷開,如網線故障等物理鏈路的原因,還有突然主機斷電等原因
有兩種方法可以檢測:1.TCP串連雙方定時發握手訊息 2.利用TCP協議棧中的KeepAlive探測
第二種方法簡單可靠,只需對TCP串連兩個Socket設定KeepAlive探測,所以本文只講第二種方法在Linux,Window2000下的實現(在其它的平台上沒有作進一步的測試)
Windows 2000平台下
//定義結構及宏
struct TCP_KEEPALIVE {
u_longonoff;
u_longkeepalivetime;
u_longkeepaliveinterval;
} ;

#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)

//KeepAlive實現
TCP_KEEPALIVE inKeepAlive = {0}; //輸入參數
unsigned long ulInLen = sizeof(TCP_KEEPALIVE);

TCP_KEEPALIVE outKeepAlive = {0}; //輸出參數
unsigned long ulOutLen = sizeof(TCP_KEEPALIVE);

unsigned long ulBytesReturn = 0;

//設定socket的keep alive為5秒,並且發送次數為3次
inKeepAlive.onoff = 1;
inKeepAlive.keepaliveinterval = 5000; //兩次KeepAlive探測間的時間間隔
inKeepAlive.keepalivetime = 5000; //開始首次KeepAlive探測前的TCP空閉時間

if (WSAIoctl((unsigned int)s, SIO_KEEPALIVE_VALS,
(LPVOID)&inKeepAlive, ulInLen,
(LPVOID)&outKeepAlive, ulOutLen,
&ulBytesReturn, NULL, NULL) == SOCKET_ERROR)
{
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%P|%t) /WSAIoctl failed. error code(%d)!/n"),WSAGetLastError()));
}

Linux平台下
#include
……
////KeepAlive實現
//下面代碼要求有ACE,如果沒有包含ACE,則請把用到的ACE函數改成linux相應的介面
int keepAlive = 1;//設定KeepAlive
int keepIdle = 5;//開始首次KeepAlive探測前的TCP空閉時間
int keepInterval = 5;//兩次KeepAlive探測間的時間間隔
int keepCount = 3;//判定斷開前的KeepAlive探測次數

if(setsockopt(s,SOL_SOCKET,SO_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_TEXT ("(%P|%t)setsockopt TCP_KEEPCNT error!/n")));
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.