- #include <mstcpip.h>
-
- bool IsConnectedByKeepAlive(SOCKET s)
- {
- BOOL bKeepAlive = TRUE;
- int nRet = setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE,(char*)&bKeepAlive, sizeof(bKeepAlive));
- if (nRet == SOCKET_ERROR)
- {
- TRACE(L"setsockopt failed: %d\n", WSAGetLastError());
- return FALSE;
- }
- // set KeepAlive parameter
- tcp_keepalive alive_in;
- tcp_keepalive alive_out;
- alive_in.keepalivetime = 5000; // 通信正常的情况下每隔5s发送一次心跳包
- alive_in.keepaliveinterval = 1000; //如果发送心跳包没有收到回复,则每隔1秒重发,直到收到回复为止,如果默认发了10次没有收到回复,则SOCKET断开
- alive_in.onoff = TRUE; //启用保活
- unsigned long ulBytesReturn = 0;
- nRet = WSAIoctl(m_socket, SIO_KEEPALIVE_VALS, &alive_in, sizeof(alive_in),
- &alive_out, sizeof(alive_out), &ulBytesReturn, NULL, NULL);
- if (nRet == SOCKET_ERROR)
- {
- TRACE(L"WSAIoctl failed: %d\n", WSAGetLastError());
- return FALSE;
- }
- return true;
- }
注:查看TCP连接的命令:netstat -an