C# 獲取本機 傳送/接收 子節的速度
阿新 • • 發佈:2018-12-20
在該方法中的主要工作過程是先遍歷網絡卡列表並獲取接受和傳送的位元組數,然後通過邏輯運算獲取本次接收和傳送的位元組數
主要用到了NetworkInterface類以及另一個類IPv4InterfaceStatistics
在使用前先宣告名稱空間
using System.Net;
例項程式碼
NetworkInterface[] group = NetworkInterface.GetAllNetworkInterfaces(); //上一次接收/傳送的位元組數 long lastReived = 0; long lastSent = 0; while (true) { //本次接收/傳送的位元組數 long Received = 0; long Sent = 0; foreach (NetworkInterface net in group) { IPv4InterfaceStatistics interfaceStats = net.GetIPv4Statistics(); if(interfaceStats.BytesReceived == 0 && interfaceStats.BytesSent == 0) { continue; } //本次接收/傳送位元組數 累加 Received += interfaceStats.BytesReceived; Sent += interfaceStats.BytesSent; //計算接收/傳送的位元組數 本次-上次 long receivedSpeed = Received - lastReived; long sentSpeed = Sent - lastSent; //上次接收為0時 速度為0 if (lastReived == 0 && lastSent == 0) { receivedSpeed = 0; sentSpeed = 0; } //顯示速度 Console.WriteLine(DateTime.Now.ToString() + "\t\t\t" + "Recived : " + receivedSpeed / 1024 + " KB/s <-> Sent : " + sentSpeed /1024+ "KB/s"); //記錄上一次接收/傳送的位元組 lastReived = Received; lastSent = Sent; } //間隔1秒 Thread.Sleep(1000); Console.WriteLine();