I have been trying to display current IPv6 connections with the GetExtendedTcpTable()
method from Windows, but I'm not getting it to display any IPv6 Adresses.
I only found code on how to display current IPv4 connections, so what I did is change the IPv4 methods to IPv6 methods of the Windows documentation.
I also tried other methods, like PMIB_TCP6ROW_OWNER_MODULE
, but it just wont show the IPv6 adresses.
Information about the PID is saved in ptTable
, but ucLocalAddr
or usRemoteAddr
isn't returning anything.
Code looks like this:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <iostream>
#include <vector>
#include <in6addr.h>
#include <Ws2ipdef.h>
#include < ws2tcpip.h>
#pragma comment(lib,"psapi")
#pragma comment(lib,"iphlpapi")
#pragma comment(lib,"wsock32")
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
vector<unsigned char> buffer2;
DWORD dwSize2 = sizeof(MIB_TCP6TABLE_OWNER_PID);
UCHAR dwSize3 = sizeof(MIB_TCP6TABLE_OWNER_PID);
DWORD dwRetValue2 = 0;
do
{
buffer2.resize(dwSize3, 0);
dwRetValue2 = GetExtendedTcpTable(buffer2.data(), &dwSize2, TRUE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0);
} while (dwRetValue2 == ERROR_INSUFFICIENT_BUFFER);
if (dwRetValue2 == ERROR_SUCCESS)
{
PMIB_TCP6TABLE_OWNER_PID ptTable = reinterpret_cast<PMIB_TCP6TABLE_OWNER_PID>(buffer2.data());
cout << "Number of Entries: " << ptTable->dwNumEntries << endl << endl;
// caution: array starts with index 0, count starts by 1
for (DWORD i = 0; i < ptTable->dwNumEntries; i )
{
DWORD pid = ptTable->table[i].dwOwningPid;
UCHAR* lol = ptTable->table[i].ucLocalAddr;
printf("%s", "--------------------------------\n");
printf("%s", ptTable->table[i].ucLocalAddr);
cout << "PID: " << ptTable->table[i].dwOwningPid << endl;
cout << "State: " << ptTable->table[i].dwState << endl;
cout << "Local: "
<< (ptTable->table[i].ucLocalAddr)
<< ":"
<< ((ptTable->table[i].ucLocalAddr))
<< ":"
<< ((ptTable->table[i].ucLocalAddr))
<< ":"
<< ((ptTable->table[i].ucLocalAddr))
<< ":"
<< htons((unsigned short)ptTable->table[i].dwLocalPort)
<< endl;
cout << "Remote: "
<< (ptTable->table[i].ucRemoteAddr)
<< ":"
<< ((ptTable->table[i].ucRemoteAddr))
<< ":"
<< ((ptTable->table[i].ucRemoteAddr))
<< ":"
<< ((ptTable->table[i].ucRemoteAddr))
<< ":"
<< htons((unsigned short)ptTable->table[i].dwRemotePort)
<< endl;
cout << endl;
}
}
cin.get();
}
CodePudding user response:
Your do
loop is not expanding the vector
correctly, it resizes the vector
to the same value on each iteration. Get rid of dwSize3
and use dwSize2
for both the resize and the enumeration.
Also, since you are retrieving AF_INET6
entries, each IPv6 address in the table is 16 bytes in size, but you are not even displaying any of the bytes correctly. The IP addresses are provided as raw bytes, not as strings. Fortunately, the API has functions for that conversion, per the
It runs well.