#include <algorithm>
#include "iphlpapi.h"
#pragma comment(lib, "Iphlpapi.lib")
vector<unsigned short> GetAllUsedTcpPort()
{
std::vector<unsigned short> result;
ULONG size = 0;
GetTcpTable(NULL, &size, TRUE);
char *pBuffer = new char[size];
PMIB_TCPTABLE tcpTable = reinterpret_cast<PMIB_TCPTABLE>(pBuffer);
if (GetTcpTable(tcpTable, &size, FALSE) == NO_ERROR)
{
for (size_t i = 0; i < tcpTable->dwNumEntries; i++)
{
result.push_back(ntohs((unsigned short)tcpTable->table[i].dwLocalPort));
}
}
delete pBuffer;
pBuffer = nullptr;
return result;
}
vector<unsigned short> GetAllUsedUdpPort()
{
std::vector<unsigned short> result;
ULONG size = 0;
GetUdpTable(NULL, &size, TRUE);
char *pBuffer = new char[size];
PMIB_UDPTABLE updTable = reinterpret_cast<PMIB_UDPTABLE>(pBuffer);
if (GetUdpTable(updTable, &size, FALSE) == NO_ERROR)
{
for (size_t i = 0; i < updTable->dwNumEntries; i++)
{
result.push_back(ntohs((unsigned short)updTable->table[i].dwLocalPort));
}
}
delete pBuffer;
pBuffer = nullptr;
return result;
}