- 获取tcp的连接信息 模拟netstat,此处只获取本地开放的端口
- 获取tcp的连接信息 模拟netstat,此处只获取本地开发的端口
- vector<int> VengConfig::EnumTCPTable()
- {
- vector<int> nOpenPort;
- PMIB_TCPTABLE pTcpTable = NULL;
- DWORD dwSize = 0;
- DWORD dwRetVal = ERROR_SUCCESS;
- struct in_addr rip;
- struct in_addr lip;
- char szrip[32] = {0};
- char szlip[32] = {0};
- char sLocalIP[32]={0},sRemoteIP[32]={0};
- u_short nLocalPort = 0;
- pTcpTable = (MIB_TCPTABLE *) MALLOC(sizeof(MIB_TCPTABLE2));
- if (pTcpTable == NULL) {
- printf("Error allocating memory\n");
- return nOpenPort;
- }
- dwSize = sizeof (MIB_TCPTABLE);
- if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) ==
- ERROR_INSUFFICIENT_BUFFER) {
- FREE(pTcpTable);
- pTcpTable = (MIB_TCPTABLE *) MALLOC(dwSize);
- if (pTcpTable == NULL) {
- printf("Error allocating memory\n");
- return nOpenPort;
- }
- }
- string TmpStr;
- if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR)
- {
- for (int i = 0; i < (int) pTcpTable->dwNumEntries; i++)
- {
- rip.S_un.S_addr = pTcpTable->table[i].dwRemoteAddr;
- lip.S_un.S_addr = pTcpTable->table[i].dwLocalAddr;
- if (pTcpTable->table[i].dwState == MIB_TCP_STATE_LISTEN)
- pTcpTable->table[i].dwRemotePort = 0;
- strcpy_s(sLocalIP,inet_ntoa(lip));
- if ( !strcmp(sLocalIP,"127.0.0.1") )
- {
- continue;
- }
- nLocalPort = htons((u_short)pTcpTable->table[i].dwLocalPort);
- char cPortBuf[10] = {0};
- sprintf_s(cPortBuf,"%d",nLocalPort);
- if ( TmpStr.find(cPortBuf) == -1 )
- {
- nOpenPort.push_back(nLocalPort);
- }
- TmpStr = TmpStr + cPortBuf +",";
- //sprintf_s(szlip,sizeof(szlip),"%s:%d",inet_ntoa(lip),nLocalPort);
- //strcpy_s(sRemoteIP,inet_ntoa(rip));
- //sprintf_s(szrip,sizeof(szrip),"%s:%d",inet_ntoa(rip),htons((u_short)pTcpTable->table[i].dwRemotePort));
- //printf("TCP\t%-24s%-24s%s\r\n",szlip,szrip,TcpState[pTcpTable->table[i].dwState]);
- }
- sort(nOpenPort.begin(),nOpenPort.end());
- }
- else
- {
- printf("\tGetTcpTable failed with %d\n", dwRetVal);
- FREE(pTcpTable);
- return nOpenPort;
- }
- if (pTcpTable != NULL) {
- FREE(pTcpTable);
- pTcpTable = NULL;
- }
- return nOpenPort;
- }
转载于:https://blog.51cto.com/venglu/1185216