Skip to content

Instantly share code, notes, and snippets.

@kyle-go
Created December 6, 2019 06:53
Show Gist options
  • Save kyle-go/2ff369373e1de7ffea82f80b46559797 to your computer and use it in GitHub Desktop.
Save kyle-go/2ff369373e1de7ffea82f80b46559797 to your computer and use it in GitHub Desktop.
netstat -ano -p tcp 枚举TCP链接
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>
#include <Iphlpapi.h>
#include <tlhelp32.h>
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "WS2_32.lib")
int main()
{
PMIB_TCPTABLE_OWNER_PID pTcpTable(NULL);
DWORD dwSize = 0;
GetExtendedTcpTable(pTcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
pTcpTable = (MIB_TCPTABLE_OWNER_PID *)new char[dwSize];//重新分配缓冲区
if (GetExtendedTcpTable(pTcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != NO_ERROR)
{
delete pTcpTable;
return 0;
}
for (DWORD i = 0; i < pTcpTable->dwNumEntries; i++)
{
char szLocal[64] = { 0 };
char szRemote[64] = { 0 };
strcpy(szLocal, inet_ntoa(*(in_addr*)& pTcpTable->table[i].dwLocalAddr));
strcpy(szRemote, inet_ntoa(*(in_addr*)& pTcpTable->table[i].dwRemoteAddr));
printf("%d 本地地址:%s:%d 远程地址:%s:%d 状态:%d 进程ID:%d\r\n",
i,
szLocal, //本地IP 地址
htons(pTcpTable->table[i].dwLocalPort), //本地端口
szRemote, //远程IP地址
htons(pTcpTable->table[i].dwRemotePort), //远程端口
pTcpTable->table[i].dwState, //状态
pTcpTable->table[i].dwOwningPid); //所属进程PID
}
delete pTcpTable;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment