GetExtendedTcpTable 是一个 Windows API 函数,用于检索包含 TCP 终结点列表的表。这个函数可以提供关于系统中活动的 TCP 连接的详细信息,包括本地和远程地址、端口、进程 ID(PID)以及连接状态等

#include <windows.h>
#include <iphlpapi.h>
#include <iostream>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

int main()
{
    DWORD dwSize = 0;
    DWORD nCode = GetExtendedTcpTable(NULL, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
    if (nCode != ERROR_INSUFFICIENT_BUFFER) {
        std::cerr << "Failed to determine buffer size." << std::endl;
        return 1;
    }

    PMIB_TCPTABLE_OWNER_PID tcpTable = (PMIB_TCPTABLE_OWNER_PID)malloc(dwSize);
    if (tcpTable == NULL) {
        std::cerr << "Memory allocation failed." << std::endl;
        return 1;
    }
    // AF_INET: ipv4, AF_INET6: ipv6
    nCode = GetExtendedTcpTable(tcpTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
    if (nCode != NO_ERROR) {
        free(tcpTable);
        std::cerr << "GetExtendedTcpTable call failed. Error code: " << nCode << std::endl;
        return 1;
    }

    for (DWORD i = 0; i < tcpTable->dwNumEntries; ++i) {
        in_addr addrLocal;
        addrLocal.S_un.S_addr = (u_long)tcpTable->table[i].dwLocalAddr;
        u_short nSrcPort = ntohs(tcpTable->table[i].dwLocalPort);

        in_addr addrRemote;
        addrRemote.S_un.S_addr= (u_long)tcpTable->table[i].dwRemoteAddr;
        u_short nRemotePort = ntohs(tcpTable->table[i].dwRemotePort);
        std::cout << "Local Addr: " << std::string(inet_ntoa(addrLocal))
            << ", Local Port: " << nSrcPort
            << ", Remote Addr: " << std::string(inet_ntoa(addrRemote))
            << ", Remote Port: " << nRemotePort
            << ", PID: " << tcpTable->table[i].dwOwningPid
            << ", State: " << tcpTable->table[i].dwState << std::endl;

       
#if 0
        // delete tcp connect
        if((nSrcPort != 0) && (nRemotePort != 0) && (MIB_TCP_STATE_ESTAB == tcpTable->table[i].dwState))
        {
            MIB_TCPROW rowTCP;
            rowTCP.dwLocalAddr = tcpTable->table[i].dwLocalAddr;
            rowTCP.dwLocalPort = tcpTable->table[i].dwLocalPort;
            rowTCP.dwRemoteAddr = tcpTable->table[i].dwRemoteAddr;
            rowTCP.dwRemotePort = tcpTable->table[i].dwRemotePort;
            rowTCP.dwState = MIB_TCP_STATE_DELETE_TCB;
            // SetTcpEntry only support ipv4, 
            // ipv6: https://bbs.huorong.cn/archiver/?tid-98857.html
            DWORD dwrst = SetTcpEntry(&rowTCP);
        }
#endif
    }

    free(tcpTable);
    getchar();
    return 0;
}
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐