C++ 使用 PdhAddCounter 获取特定进程网络流量
使用 PdhAddCounter 函数获取特定进程的网络发送和接收流量,需要执行以下步骤:
- 初始化性能数据计数器。使用 PdhOpenQuery 函数创建一个查询句柄,并使用 PdhAddCounter 函数添加要监视的计数器。
#include <pdh.h>
#pragma comment(lib, "pdh.lib")
PDH_HQUERY hQuery;
PDH_HCOUNTER hSentCounter, hReceivedCounter;
PdhOpenQuery(NULL, NULL, &hQuery);
PdhAddCounter(hQuery, "\Process(<进程名>)\IO Data Bytes/sec", NULL, &hSentCounter);
PdhAddCounter(hQuery, "\Process(<进程名>)\IO Other Bytes/sec", NULL, &hReceivedCounter);
- 收集性能数据。使用 PdhCollectQueryData 函数获取计数器的当前值。
PdhCollectQueryData(hQuery);
- 获取计数器的值。使用 PdhGetFormattedCounterValue 函数获取计数器的值。
PDH_FMT_COUNTERVALUE counterValueSent, counterValueReceived;
PdhGetFormattedCounterValue(hSentCounter, PDH_FMT_LONG, NULL, &counterValueSent);
PdhGetFormattedCounterValue(hReceivedCounter, PDH_FMT_LONG, NULL, &counterValueReceived);
DWORD sentBytes = counterValueSent.longValue;
DWORD receivedBytes = counterValueReceived.longValue;
- 关闭查询句柄。使用 PdhCloseQuery 函数关闭查询句柄。
PdhCloseQuery(hQuery);
请注意,上述代码中的<进程名>应替换为要监视的进程的名称。此外,还需要包含 pdh.h 头文件并链接 pdh.lib 库文件。
原文地址: https://www.cveoy.top/t/topic/fSyx 著作权归作者所有。请勿转载和采集!