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\n\n");
 printf("  Proto\t%-24s%-24s%s\n","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\n",szlip,szrip,TcpState[pTcpTable->table[i].dwState]);
  }
 }
 else
 {
  printf("\tCall to GetTcpTable failed.\n");
   
  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();
}


 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值