用c++代码获取本机带宽使用占比,不使用GetPerTcpConnectionEStats、MIB_IF_ROW2
时间: 2024-02-10 16:10:58 浏览: 276
你可以使用Windows Performance Counters来获取本机带宽使用占比。下面是一个获取网络传输速率的示例代码:
```c++
#include <Windows.h>
#include <iostream>
int main()
{
PDH_STATUS status;
PDH_HQUERY query;
PDH_HCOUNTER counterTx, counterRx;
PDH_FMT_COUNTERVALUE valueTx, valueRx;
ULONGLONG lastTx = 0, lastRx = 0;
ULONGLONG currentTx, currentRx;
double txRate, rxRate;
status = PdhOpenQuery(NULL, NULL, &query);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhOpenQuery failed with error " << status << std::endl;
return 1;
}
status = PdhAddCounter(query, L"\\Network Interface(*)\\Bytes Sent/sec", NULL, &counterTx);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhAddCounter (TX) failed with error " << status << std::endl;
return 1;
}
status = PdhAddCounter(query, L"\\Network Interface(*)\\Bytes Received/sec", NULL, &counterRx);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhAddCounter (RX) failed with error " << status << std::endl;
return 1;
}
status = PdhCollectQueryData(query);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhCollectQueryData failed with error " << status << std::endl;
return 1;
}
Sleep(1000);
status = PdhCollectQueryData(query);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhCollectQueryData failed with error " << status << std::endl;
return 1;
}
status = PdhGetFormattedCounterValue(counterTx, PDH_FMT_LARGE, NULL, &valueTx);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhGetFormattedCounterValue (TX) failed with error " << status << std::endl;
return 1;
}
currentTx = valueTx.largeValue;
status = PdhGetFormattedCounterValue(counterRx, PDH_FMT_LARGE, NULL, &valueRx);
if (status != ERROR_SUCCESS) {
std::cerr << "PdhGetFormattedCounterValue (RX) failed with error " << status << std::endl;
return 1;
}
currentRx = valueRx.largeValue;
txRate = (currentTx - lastTx) / 1024.0;
rxRate = (currentRx - lastRx) / 1024.0;
std::cout << "TX Rate: " << txRate << " KB/s" << std::endl;
std::cout << "RX Rate: " << rxRate << " KB/s" << std::endl;
lastTx = currentTx;
lastRx = currentRx;
PdhCloseQuery(query);
return 0;
}
```
该代码使用了Windows的性能计数器来获取网络接口的传输速率。你可以根据需要修改计数器路径以获取其他信息。注意,在实际应用中,你可能需要更复杂的逻辑来计算带宽使用占比。
阅读全文