How can I access netstat-like Ethernet statistics from a Windows program

前端 未结 7 1961
臣服心动
臣服心动 2020-12-03 16:11

How can I access Ethernet statistics from C/C++ code like netstat -e?

Interface Statistics

                       Received            Sent
         


        
相关标签:
7条回答
  • 2020-12-03 16:54

    Let me answer to myself, as I asked the same on another forum.

    WMI is good, but it's easier to use IpHlpApi instead:

    #include <winsock2.h>
    #include <iphlpapi.h>
    
    int main(int argc, char *argv[])
    {
    
    PMIB_IFTABLE pIfTable;
    MIB_IFROW ifRow;
    PMIB_IFROW pIfRow = &ifRow;
    DWORD dwSize = 0;
    
    // first call returns the buffer size needed
    DWORD retv = GetIfTable(pIfTable, &dwSize, true);
    if (retv != ERROR_INSUFFICIENT_BUFFER)
        WriteErrorAndExit(retv);
    pIfTable = (MIB_IFTABLE*)malloc(dwSize);
    
    retv = GetIfTable(pIfTable, &dwSize, true);
    if (retv != NO_ERROR)
        WriteErrorAndExit(retv);
    
    // Get index
        int i,j;
        printf("\tNum Entries: %ld\n\n", pIfTable->dwNumEntries);
        for (i = 0; i < (int) pIfTable->dwNumEntries; i++)
        {
            pIfRow = (MIB_IFROW *) & pIfTable->table[i];
            printf("\tIndex[%d]:\t %ld\n", i, pIfRow->dwIndex);
            printf("\tInterfaceName[%d]:\t %ws", i, pIfRow->wszName);
            printf("\n");
            printf("\tDescription[%d]:\t ", i);
            for (j = 0; j < (int) pIfRow->dwDescrLen; j++)
                printf("%c", pIfRow->bDescr[j]);
            printf("\n");
            ...
    
    0 讨论(0)
提交回复
热议问题