获取本地tcp连接状态,cmd里的netstat,找到自己的tcp连接。
DWORD m_dwLocalIP = 212123; // 本地ip
bool GetEp2TcpState()
{
PMIB_TCPTABLE pTcpTable = NULL;
DWORD dwActualSize = 0;
// 查询所需缓冲区的大小
if (::GetTcpTable(pTcpTable, &dwActualSize, true) == ERROR_INSUFFICIENT_BUFFER)
{
// 为MIB_TCPTABLE结构申请内存
pTcpTable = (PMIB_TCPTABLE)::GlobalAlloc(GPTR, dwActualSize);
// 获取TCP连接表
if (::GetTcpTable(pTcpTable, &dwActualSize, true) == NO_ERROR)
{
if (pTcpTable != NULL)
{
char strState[128];
struct in_addr inadLocal, inadRemote;
//char szLocalIp[128];
char szRemIp[128];
for (UINT i = 0; i < pTcpTable->dwNumEntries; ++i)
{
if (m_dwLocalIP != pTcpTable->table[i].dwLocalAddr)
{
continue;
}
u_short port = ntohs((unsigned short)(0x0000FFFF & pTcpTable->table[i].dwRemotePort));
inadRemote.s_addr = pTcpTable->table[i].dwRemoteAddr;
strcpy(szRemIp, inet_ntoa(inadRemote));
if (port ==9000)
{
if (pTcpTable->table[i].dwState== MIB_TCP_STATE_ESTAB)
{
::GlobalFree(pTcpTable);
return true;
}
break;
}
}
}
}
::GlobalFree(pTcpTable);
}
return false;
}
int main()
{
bool status = GetEp2TcpState();
return 0;
}