在该方法中的主要工作过程是先遍历网卡列表并获取接受和发送的字节数,然后通过逻辑运算获取本次接收和发送的字节数
主要用到了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();