Netstatソースコード(場所)


#include "Winsock2.h"
#include "Iphlpapi.h"
#include <malloc.h>
#include <stdlib.h>
#include <stdio.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()
{
 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};
 
 // pTcpTable ,dwSize
 if (GetTcpTable(pTcpTable, &dwSize, TRUE) == ERROR_INSUFFICIENT_BUFFER)
 {
  pTcpTable = (MIB_TCPTABLE*) malloc ((UINT) dwSize);
 }
 else
  return dwRetVal;

 printf("Active Connections

"); printf(" Proto\t%-24s%-24s%s
","Local Address","Foreign Address","State"); 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; // , 0, , if (pTcpTable->table[i].dwState == MIB_TCP_STATE_LISTEN) pTcpTable->table[i].dwRemotePort = 0; //dwLocalPort,dwRemotePort _snprintf(szlip,sizeof(szlip),"%s:%d",inet_ntoa(lip),htons((u_short)pTcpTable->table[i].dwLocalPort)); _snprintf(szrip,sizeof(szrip),"%s:%d",inet_ntoa(rip),htons((u_short)pTcpTable->table[i].dwRemotePort)); printf(" TCP\t%-24s%-24s%s
",szlip,szrip,TcpState[pTcpTable->table[i].dwState]); } } else { printf("\tCall to GetTcpTable failed.
"); LPVOID lpMsgBuf; if (FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL )) { printf("\tError: %s", lpMsgBuf); } LocalFree( lpMsgBuf ); } GlobalFree(pTcpTable); return dwRetVal; } void main() { EnumTCPTable(); }