代码之家  ›  专栏  ›  技术社区  ›  user2219913

如何使用GetTcpIPv4Statistics[已关闭]

  •  -2
  • user2219913  · 技术社区  · 11 年前

    我想获取TCP/UDP IPv4统计信息。我瑟瑟发抖,发现 GetTcpIPv4Statistics API那么,如何使用它在c++代码中获取TCP/UDP统计信息呢?

    2 回复  |  直到 11 年前
        1
  •  5
  •   Alex K.    11 年前

    这似乎只是一个.net方法,它调用底层 GetTcpStatisticsEx IP Helper API,它是您希望从非托管C++中使用的。

        2
  •  4
  •   user2219913    11 年前

    我解决了这个问题。为了获得IPV4的TCP统计信息,我使用了以下代码:

    #include "stdafx.h"
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <iphlpapi.h>
    #include <stdio.h>
    
    #pragma comment(lib, "iphlpapi.lib")
    
    #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) 
    #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
    
    /* Note: could also use malloc() and free() */
    
    int main()
    {
        PMIB_TCPSTATS pTCPStats;
        DWORD dwRetVal = 0;
    
        pTCPStats = (MIB_TCPSTATS*) MALLOC (sizeof(MIB_TCPSTATS));
        if (pTCPStats == NULL) {
            printf("Error allocating memory\n");
            return 1;
        }
    
        if ((dwRetVal = GetTcpStatisticsEx(pTCPStats,AF_INET)) == NO_ERROR) {
          printf("\tActive Opens: %ld\n", pTCPStats->dwActiveOpens);
          printf("\tPassive Opens: %ld\n", pTCPStats->dwPassiveOpens);
          printf("\tSegments Recv: %ld\n", pTCPStats->dwInSegs);
          printf("\tSegments Xmit: %ld\n", pTCPStats->dwOutSegs);
          printf("\tTotal # Conxs: %ld\n", pTCPStats->dwAttemptFails);
          printf("\tAttemp failed: %ld\n", pTCPStats->dwAttemptFails);
          printf("\tcurr estab: %ld\n", pTCPStats->dwCurrEstab);
          printf("\testab reset: %ld\n", pTCPStats->dwEstabResets);
          printf("\tIn err: %ld\n", pTCPStats->dwInErrs);
          printf("\tmax conn: %ld\n", pTCPStats->dwMaxConn);
          printf("\tNum conn: %ld\n", pTCPStats->dwNumConns);
          printf("\tout rst: %ld\n", pTCPStats->dwOutRsts);
          printf("\tretrans seg: %ld\n", pTCPStats->dwRetransSegs);
           printf("\tRtoAlgorithm: %ld\n", pTCPStats->dwRtoAlgorithm);
            printf("\RtoMax: %ld\n", pTCPStats->dwRtoMax);
             printf("\RtoMin: %ld\n", pTCPStats->dwRtoMin);
              printf("\RtoAlgorithm: %ld\n", pTCPStats->RtoAlgorithm);
        }
        else {
          printf("GetTcpStatistics failed with error: %ld\n", dwRetVal);
    
          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 );
        }
    
        if (pTCPStats)
            FREE (pTCPStats);
        system("pause");
    }
    

    为了获得IPv6的统计数据,我只替换 AF_INET 通过 AF_INET6