#include "Iphlpapi.h"
#pragma comment(lib,"Iphlpapi.lib")
#pragma comment(lib,"ws2_32.lib")
PMIB_TCPTABLE MyGetTcpTable(BOOL bOrder)
{
PMIB_TCPTABLE pTcpTable = NULL;
DWORD dwActualSize = 0;
if(::GetTcpTable(pTcpTable, &dwActualSize, bOrder) == ERROR_INSUFFICIENT_BUFFER)
{
pTcpTable = (PMIB_TCPTABLE)::GlobalAlloc(GPTR, dwActualSize);
if(::GetTcpTable(pTcpTable, &dwActualSize, bOrder) == NO_ERROR)
return pTcpTable;
::GlobalFree(pTcpTable);
}
return NULL;
}
void MyFreeTcpTable(PMIB_TCPTABLE pTcpTable)
{
if(pTcpTable != NULL)
::GlobalFree(pTcpTable);
}
char* Tcp()
{
PMIB_TCPTABLE pTcpTable = MyGetTcpTable(TRUE);
char szBuf[14096]="";
if(pTcpTable != NULL)
{
char strState[12800];
struct in_addr inadLocal, inadRemote;
DWORD dwRemotePort = 0;
char szLocalIp[128];
char szRemIp[128];
sprintf(szBuf,"TCP TABLE\n");
for(UINT i = 0; i < pTcpTable->dwNumEntries; ++i)
{
// ??
switch (pTcpTable->table[i].dwState)
{
case MIB_TCP_STATE_CLOSED:
strcpy(strState, "CLOSED");
break;
case MIB_TCP_STATE_TIME_WAIT:
strcpy(strState, "TIME_WAIT");
break;
case MIB_TCP_STATE_LAST_ACK:
strcpy(strState, "LAST_ACK");
break;
case MIB_TCP_STATE_CLOSING:
strcpy(strState, "CLOSING");
break;
case MIB_TCP_STATE_CLOSE_WAIT:
strcpy(strState, "CLOSE_WAIT");
break;
case MIB_TCP_STATE_FIN_WAIT1:
strcpy(strState, "FIN_WAIT1");
break;
case MIB_TCP_STATE_ESTAB:
strcpy(strState, "ESTAB");
break;
case MIB_TCP_STATE_SYN_RCVD:
strcpy(strState, "SYN_RCVD");
break;
case MIB_TCP_STATE_SYN_SENT:
strcpy(strState, "SYN_SENT");
break;
case MIB_TCP_STATE_LISTEN:
strcpy(strState, "LISTEN");
break;
case MIB_TCP_STATE_DELETE_TCB:
strcpy(strState, "DELETE");
break;
default:
strcpy(strState,"Error: unknown state!\n");
break;
}
// 本地地址
inadLocal.s_addr = pTcpTable->table[i].dwLocalAddr;
// ?程端口
if (strcmp(strState, "LISTEN") != 0)
{
dwRemotePort = pTcpTable->table[i].dwRemotePort;
}
else
dwRemotePort = 0;
// ?程IP地址
inadRemote.s_addr = pTcpTable->table[i].dwRemoteAddr;
if(inadLocal.S_un.S_addr != 0 && inadLocal.S_un.S_addr != 0x100007f)
{
strcpy(szLocalIp, inet_ntoa(inadLocal));
strcpy(szRemIp, inet_ntoa(inadRemote));
sprintf(szBuf,"%20s %10u %20s %10u %s\n",
szLocalIp, ntohs((unsigned short)(0x0000FFFF & pTcpTable->table[i].dwLocalPort)),
szRemIp, ntohs((unsigned short)(0x0000FFFF & dwRemotePort)),
strState);
return szLocalIp;
}
}
MyFreeTcpTable(pTcpTable);
}
return "127.0.0.1";;
}