windows10下获取特定进程网络流量的发送和接收速率C++代码
以下是一个示例代码,用于获取Windows 10中特定进程的网络流量的发送和接收速率:
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
#include <tchar.h>
#include <vector>
// 获取特定进程的网络流量信息
void GetProcessNetworkUsage(DWORD processId, ULONGLONG& sentBytes, ULONGLONG& receivedBytes)
{
MIB_TCPTABLE_OWNER_PID tcpTable;
DWORD dwSize = sizeof(tcpTable);
// 获取TCP连接表
if (GetExtendedTcpTable(&tcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == ERROR_INSUFFICIENT_BUFFER)
{
free(tcpTable.table);
tcpTable.table = (MIB_TCPROW_OWNER_PID*)malloc(dwSize);
}
// 重新获取TCP连接表
if (GetExtendedTcpTable(&tcpTable, &dwSize, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR)
{
// 遍历TCP连接表,查找特定进程的网络流量
for (DWORD i = 0; i < tcpTable.dwNumEntries; i++)
{
if (tcpTable.table[i].dwOwningPid == processId)
{
sentBytes += tcpTable.table[i].dwBytesSent;
receivedBytes += tcpTable.table[i].dwBytesReceived;
}
}
}
free(tcpTable.table);
}
int main()
{
DWORD processId = 0; // 要获取网络流量的进程ID
ULONGLONG sentBytes = 0; // 发送的字节数
ULONGLONG receivedBytes = 0; // 接收的字节数
// 获取进程ID
HWND hwnd = FindWindow(NULL, _T("窗口标题"));
if (hwnd != NULL)
{
GetWindowThreadProcessId(hwnd, &processId);
}
// 获取网络流量信息
GetProcessNetworkUsage(processId, sentBytes, receivedBytes);
std::cout << "Sent Bytes: " << sentBytes << std::endl;
std::cout << "Received Bytes: " << receivedBytes << std::endl;
return 0;
}
请注意,您需要将“窗口标题”更改为要获取网络流量的进程的窗口标题。此代码使用Windows API函数GetExtendedTcpTable来获取TCP连接表,并使用GetWindowThreadProcessId函数获取特定窗口的进程ID。然后,它遍历TCP连接表,查找具有相同进程ID的连接,并累积发送和接收的字节数。最后,它打印出发送和接收的字节数。
原文地址: http://www.cveoy.top/t/topic/idY9 著作权归作者所有。请勿转载和采集!