关于查看本机端口信息,可能大多数人都知道在cmd下的netstat 命令,殊不知该命令在底层也是调用相关api来实现的,
相关函数有:GetTcpTableGetExtendedTcpTableGetUdpTableGetExtendedUdpTable这些函数就可以获取相关tcp、udp端口以及相关进程的信息。而且这些函数都是从Iphlpapi.dll里导出的。函数的相关用法可查询msdn在掌握,下面封装一段代码,来枚举每机的所有监听端口
#include "stdafx.h"#include#include #include #include #include #include #pragma comment(lib, "iphlpapi.lib")#pragma comment(lib, "ws2_32.lib")using namespace std;#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))BOOL GetLocalListeningPort(list
& listPort);int _tmain(int argc, _TCHAR* argv[]){ list portArray; GetLocalListeningPort(portArray); for (list ::iterator it = portArray.begin(); it != portArray.end(); it++) { WORD port = *it; printf("listenPort:%d\n", port); } return 0;}BOOL GetLocalListeningPort(list & listPort){ PMIB_TCPTABLE pTcpTable; DWORD dwSize = 0; DWORD dwRetVal = 0; BOOL bRet = FALSE; char szLocalAddr[128]; char szBuf[128] = { 0 }; pTcpTable = (PMIB_TCPTABLE)szBuf; dwSize = 128 * sizeof(char); struct in_addr IpAddr; int i; if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == ERROR_INSUFFICIENT_BUFFER) { pTcpTable = (MIB_TCPTABLE *)MALLOC(dwSize); if (pTcpTable == NULL) { printf("Error allocating memory\n"); return bRet; } } if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR) { printf("Number of entries: %d\n", pTcpTable->dwNumEntries); for (i = 0; i < (int)pTcpTable->dwNumEntries; i++) { IpAddr.S_un.S_addr = (u_long)pTcpTable->table[i].dwLocalAddr; strcpy_s(szLocalAddr, sizeof (szLocalAddr), inet_ntoa(IpAddr)); printf("local info: %s:%d \t", szLocalAddr, ntohs((u_short)pTcpTable->table[i].dwLocalPort)); printf(" TCP[%d] State: %ld - ", i, pTcpTable->table[i].dwState); switch (pTcpTable->table[i].dwState) { case MIB_TCP_STATE_CLOSED: printf("CLOSED \n"); break; case MIB_TCP_STATE_LISTEN: listPort.push_back(ntohs((u_short)pTcpTable->table[i].dwLocalPort)); printf("LISTEN \n"); break; case MIB_TCP_STATE_SYN_SENT: printf("SYN-SENT \n"); break; case MIB_TCP_STATE_SYN_RCVD: printf("SYN-RECEIVED \n"); break; case MIB_TCP_STATE_ESTAB: printf("ESTABLISHED \n"); break; case MIB_TCP_STATE_FIN_WAIT1: printf("FIN-WAIT-1 \n"); break; case MIB_TCP_STATE_FIN_WAIT2: printf("FIN-WAIT-2 \n"); break; case MIB_TCP_STATE_CLOSE_WAIT: printf("CLOSE-WAIT \n"); break; case MIB_TCP_STATE_CLOSING: printf("CLOSING \n"); break; case MIB_TCP_STATE_LAST_ACK: printf("LAST-ACK \n"); break; case MIB_TCP_STATE_TIME_WAIT: printf("TIME-WAIT \n"); break; case MIB_TCP_STATE_DELETE_TCB: printf("DELETE-TCB \n"); break; default: printf("UNKNOWN dwState value \n"); break; } } } else { printf("GetTcpTable failed with %d \n", dwRetVal); goto EXIT; } bRet = TRUE;EXIT: if (pTcpTable != (PMIB_TCPTABLE)szBuf) { FREE(pTcpTable); pTcpTable = NULL; } return bRet;}
相关链接: