如何检索netstat命令的结果

时间:2013-03-19 15:52:51

标签: c++ windows netstat

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

2 个答案:

答案 0 :(得分:4)

您可以从此代码开始

int main() {
  char buf[10000];  
  FILE *p = _popen("netstat -a", "r");
  std::string s;
  for (size_t count; (count = fread(buf, 1, sizeof(buf), p));)
      s += string(buf, buf + count);
  cout<<s<<endl;    
  _pclose(p);  
}

答案 1 :(得分:3)

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

或者,您可以使用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;
}

请注意,我很久以前写过这篇文章 - 它比C ++更加C语言。如果我今天写这篇文章,我很确定我会做很多事情,至少有点不同。

相关问题