如何检索netstat命令的结果

Bac*_*cem 1 c++ windows netstat

我试图用 C++ 代码获取我的电脑中打开的端口列表。所以,我想使用 DOS 命令netstat。我已经写了这一行system("netstat -a"),但无法检索它返回的结果。

Jer*_*fin 5

您可以像从文件中一样使用FILE *results = _popen("netstat -a");然后读取结果(例如,使用、 等)resultsfreadfgets

或者,您可以用来GetTcpTable更直接地检索您需要的数据。这是一个相当完整的示例,用于检索大部分相同的数据netstat -a

#include <windows.h>
#include <iphlpapi.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

#define addr_size (3 + 3*4 + 1)   // xxx.xxx.xxx.xxx\0

char const *dotted(DWORD input) {
    char output[addr_size];

    sprintf(output, "%d.%d.%d.%d", 
        input>>24, 
        (input>>16) & 0xff, 
        (input>>8)&0xff, 
        input & 0xff);
    return strdup(output);
}

int main() { 
    MIB_TCPTABLE *tcp_stats;
    MIB_UDPTABLE *udp_stats;
    DWORD size = 0;
    unsigned i;
    char const *s1, *s2;

    GetTcpTable(tcp_stats, &size, TRUE);
    tcp_stats = (MIB_TCPTABLE *)malloc(size);
    GetTcpTable(tcp_stats, &size, TRUE);

    for (i=0; i<tcp_stats->dwNumEntries; ++i) {
        printf("TCP:\t%s:%d\t%s:%d\n", 
            s1=dotted(ntohl(tcp_stats->table[i].dwLocalAddr)), 
            ntohs(tcp_stats->table[i].dwLocalPort),
            s2=dotted(ntohl(tcp_stats->table[i].dwRemoteAddr)),
            ntohs(tcp_stats->table[i].dwRemotePort));
        free((char *)s1);
        free((char *)s2);
    }
    free(tcp_stats);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这是我很久以前写的——它更像是 C,而不是 C++。如果我今天写它,我很确定我会做很多事情,至少会有所不同。