Reputation: 75
I tried to get the list of opened ports in my PC in a c++ code.So, I want to use the DOS command netstat
. I have written this line system("netstat -a")
but I can't retrieve the result that it returns.
Upvotes: 1
Views: 5175
Reputation: 582
You can start with this code
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);
}
Upvotes: 4
Reputation: 490108
You could use FILE *results = _popen("netstat -a");
and then read the results from results
like you would from a file (e.g., with fread
, fgets
, etc.)
Alternatively, you could use GetTcpTable
to retrieve the data you need more directly. Here's a reasonably complete example of retrieving most of the same data as netstat -a
will:
#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;
}
Note that I wrote this a long time ago -- it's much more C than C++. If I were writing it today, I'm pretty sure I'd do a fair number of things at least a little differently.
Upvotes: 5