獲取被佔用的端口號(C++)

#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;
}
 

發佈了53 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章