Данный код перечислит все соединения компьютера по протоколу TCP, аналогично утилите netstat: #pragma hdrstop #include <stdio.h> #include <winsock.h> #include <iphlpapi.h> //--------------------------------------------------------------------------- #define MAX_STRLEN 128 #pragma argsused void PrintTcpTable(PMIB_TCPTABLE pTcpTable) { char strState[MAX_STRLEN]; struct in_addr inadLocal, inadRemote; DWORD dwRemotePort = 0; char szLocalIp[MAX_STRLEN]; char szRemIp[MAX_STRLEN]; if (pTcpTable != NULL) { printf("TCP TABLE\r\n"); printf("%20s %10s %20s %10s %s\r\n", "Loc Addr", "Loc Port", "Rem Addr", "Rem Port", "State"); 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, "ESTABLISHED"); 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: printf("UNKNOWN\n\r"); break; } inadLocal.s_addr = pTcpTable->table[i].dwLocalAddr; if (strcmp(strState, "LISTEN") != 0) { dwRemotePort = pTcpTable->table[i].dwRemotePort; } else dwRemotePort = 0; inadRemote.s_addr = pTcpTable->table[i].dwRemoteAddr; strcpy(szLocalIp, inet_ntoa(inadLocal)); strcpy(szRemIp, inet_ntoa(inadRemote)); printf("%20s %10u %20s %10u %s\r\n", szLocalIp, ntohs((unsigned short)(0x0000FFFF & pTcpTable->table[i].dwLocalPort)), szRemIp, ntohs((unsigned short)(0x0000FFFF & dwRemotePort)), strState); } } } //--------------------------------------------------------------------------- int main(int argc, char* argv[]) { WSADATA WSAData; if (!WSAStartup(MAKEWORD(1,1),&WSAData)) { printf("WSA started seccessfully!\r\n"); PMIB_TCPTABLE pTcpTable = NULL; DWORD dwActualSize = 0; DWORD status = NO_ERROR; status = GetTcpTable(pTcpTable, &dwActualSize, TRUE); if (status == NOERROR) printf("Success!\r\n"); else if (status == ERROR_INSUFFICIENT_BUFFER) { printf("Error memory! %u %u\r\n",dwActualSize, sizeof(*pTcpTable)); pTcpTable = (PMIB_TCPTABLE) malloc(dwActualSize); status = GetTcpTable(pTcpTable, &dwActualSize, TRUE); if (status == NOERROR) printf("taki Success!\r\n"); PrintTcpTable(pTcpTable); }; if (pTcpTable) free(pTcpTable); getchar(); WSACleanup(); }; return 0; } |