C# 获取本机 发送/接收 子节的速度

在该方法中的主要工作过程是先遍历网卡列表并获取接受和发送的字节数,然后通过逻辑运算获取本次接收和发送的字节数

主要用到了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();

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值