使用 PdhAddCounter 获取指定进程的发送与接收网络流量 C++

以下是使用 PdhAddCounter 获取指定进程的发送和接收网络流量的 C++ 示例代码:

#include <iostream>
#include <windows.h>
#include <pdh.h>
#include <pdhmsg.h>

#pragma comment(lib, "pdh.lib")

int main()
{
    PDH_STATUS pdhStatus;
    PDH_HQUERY hQuery;
    PDH_HCOUNTER hCounterSent, hCounterReceived;
    PDH_FMT_COUNTERVALUE counterValueSent, counterValueReceived;

    // 初始化PDH
    pdhStatus = PdhOpenQuery(NULL, 0, &hQuery);
    if (pdhStatus != ERROR_SUCCESS)
    {
        std::cout << "PdhOpenQuery failed with error code: " << pdhStatus << std::endl;
        return 1;
    }

    // 添加发送流量计数器
    pdhStatus = PdhAddCounter(hQuery, "\Process(<进程名>)\IO Write Bytes/sec", 0, &hCounterSent);
    if (pdhStatus != ERROR_SUCCESS)
    {
        std::cout << "PdhAddCounter for sent failed with error code: " << pdhStatus << std::endl;
        return 1;
    }

    // 添加接收流量计数器
    pdhStatus = PdhAddCounter(hQuery, "\Process(<进程名>)\IO Read Bytes/sec", 0, &hCounterReceived);
    if (pdhStatus != ERROR_SUCCESS)
    {
        std::cout << "PdhAddCounter for received failed with error code: " << pdhStatus << std::endl;
        return 1;
    }

    // 收集数据
    pdhStatus = PdhCollectQueryData(hQuery);
    if (pdhStatus != ERROR_SUCCESS)
    {
        std::cout << "PdhCollectQueryData failed with error code: " << pdhStatus << std::endl;
        return 1;
    }

    // 获取发送流量数据
    pdhStatus = PdhGetFormattedCounterValue(hCounterSent, PDH_FMT_DOUBLE, NULL, &counterValueSent);
    if (pdhStatus != ERROR_SUCCESS)
    {
        std::cout << "PdhGetFormattedCounterValue for sent failed with error code: " << pdhStatus << std::endl;
        return 1;
    }

    // 获取接收流量数据
    pdhStatus = PdhGetFormattedCounterValue(hCounterReceived, PDH_FMT_DOUBLE, NULL, &counterValueReceived);
    if (pdhStatus != ERROR_SUCCESS)
    {
        std::cout << "PdhGetFormattedCounterValue for received failed with error code: " << pdhStatus << std::endl;
        return 1;
    }

    // 输出发送和接收流量数据
    std::cout << "Sent: " << counterValueSent.doubleValue << " bytes/sec" << std::endl;
    std::cout << "Received: " << counterValueReceived.doubleValue << " bytes/sec" << std::endl;

    // 关闭PDH
    PdhCloseQuery(hQuery);

    return 0;
}

请将<进程名>替换为要监视的进程名称。此代码将打开一个PDH查询,添加发送和接收流量计数器,收集数据,并输出发送和接收流量数据。请注意,此代码仅适用于Windows操作系统。

C++ 使用 PdhAddCounter 获取指定进程网络流量

原文地址: https://www.cveoy.top/t/topic/fSGh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录