#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <Iphlpapi.h>
#include <malloc.h>
#include <Winsock2.h>
#include <stdlib.h>
#include <tchar.h>
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
static char TcpState[][32] =
{
"???",
"CLOSED",
"LISTENING",
"SYN_SENT",
"SEN_RECEIVED",
"ESTABLISHED",
"FIN_WAIT",
"FIN_WAIT2",
"CLOSE_WAIT",
"CLOSING",
"LAST_ACK",
"TIME_WAIT"
};
DWORD EnumTCPTable()
{
LPVOID pBuf=NULL;
DWORD dwSize=0;
in_addr rip;
in_addr lip;
char szrip[32] = {0};
char szlip[32] = {0};
if(GetExtendedTcpTable(pBuf,&dwSize,TRUE,AF_INET,TCP_TABLE_OWNER_PID_ALL/*TCP_TABLE_OWNER_PID_CONNECTIONS*/,0)==ERROR_INSUFFICIENT_BUFFER)
{
pBuf=GlobalAlloc(GPTR,dwSize);
if(!pBuf)
return dwSize;
GetExtendedTcpTable(pBuf,&dwSize,TRUE,AF_INET,TCP_TABLE_OWNER_PID_ALL/*TCP_TABLE_OWNER_PID_CONNECTIONS*/,0);
PMIB_TCPTABLE_OWNER_PID tcpTable=(PMIB_TCPTABLE_OWNER_PID)(pBuf);
for(UINT i=0;i<tcpTable->dwNumEntries;i++)
{
int nnn = tcpTable->table[i].dwOwningPid;
int lport = tcpTable->table[i].dwLocalPort;
int Rport = tcpTable->table[i].dwRemotePort;
rip.S_un.S_addr = tcpTable->table[i].dwRemoteAddr;
lip.S_un.S_addr = tcpTable->table[i].dwLocalAddr;
_snprintf(szlip,sizeof(szlip),"%s:%d",inet_ntoa(lip),htons((u_short)tcpTable->table[i].dwLocalPort));
_snprintf(szrip,sizeof(szrip),"%s:%d",inet_ntoa(rip),htons((u_short)tcpTable->table[i].dwRemotePort));
printf(" TCP\t%-24s%-24s%s %d\n",szlip,szrip,TcpState[tcpTable->table[i].dwState],nnn);
}
GlobalFree(pBuf);
pBuf = NULL;
}
return dwSize;
system("netstat -ano|findstr 172.0.0.1:1433 >netstat.txt");
}