我想实时获取Windows网卡的下行流量、丢包率、错包率的信息,用c/c++语言
5条回答 默认 最新
churuxu 2023-07-05 14:59关注
#include <stdio.h> #include <stdlib.h> #include <winsock2.h> #include <windows.h> #include <netioapi.h> #include <locale.h> #include <inttypes.h> #pragma comment(lib, "iphlpapi.lib") void show_row(PMIB_IF_ROW2 row){ if(!row->InterfaceAndOperStatusFlags.HardwareInterface)return; if(!row->InterfaceAndOperStatusFlags.ConnectorPresent)return; wprintf(L"%ls\n", row->Alias); wprintf(L"接收字节数 %"PRIu64"\n", row->InUcastOctets); wprintf(L"发送字节数 %"PRIu64"\n", row->OutUcastOctets); wprintf(L"接收单播包数 %"PRIu64"\n", row->InUcastPkts); wprintf(L"发送单播包数 %"PRIu64"\n", row->OutUcastPkts); wprintf(L"接收多播包数 %"PRIu64"\n", row->InNUcastPkts); wprintf(L"发送多播包数 %"PRIu64"\n", row->OutNUcastPkts); wprintf(L"接收错误包数 %"PRIu64"\n", row->InErrors); wprintf(L"发送错误包数 %"PRIu64"\n", row->OutErrors); wprintf(L"接收丢包数 %"PRIu64"\n", row->InDiscards); wprintf(L"发送丢包数 %"PRIu64"\n", row->OutDiscards); ULONG64 error = row->InErrors + row->OutErrors; ULONG64 discard = row->InDiscards + row->OutDiscards; ULONG64 total = row->InUcastPkts + row->OutUcastPkts + row->InNUcastPkts + row->OutNUcastPkts + error + discard; double error_rate = total?((double)error / (double)total):0; double discard_rate = total?((double)discard / (double)total):0; wprintf(L"错误率 %.4f\n", error_rate); wprintf(L"丢包率 %.4f\n", discard_rate); printf("\n"); } void show_table(PMIB_IF_TABLE2 table){ int i; PMIB_IF_ROW2 row; for (i = 0; i < table->NumEntries; i++){ row = &table->Table[i]; show_row(row); } } void get_if_status(){ PMIB_IF_TABLE2 table; if(0 == GetIfTable2Ex(MibIfTableNormal, &table)){ show_table(table); FreeMibTable(table); }else{ printf("GetIfTable2Ex fail %d\n", (int)GetLastError()); } } int main(){ setlocale(0,""); while(1){ get_if_status(); Sleep(2000); system("cls"); } return 0; }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报