【问题标题】:NetworkInterface.GetIPv4Statistics().BytesReceived - What does it return?NetworkInterface.GetIPv4Statistics().BytesReceived - 它返回什么?
【发布时间】:2012-11-14 19:06:51
【问题描述】:

该特定字段返回什么?我想要每秒接收的字节数。我应该依赖这个吗?

【问题讨论】:

    标签: c# .net networking ip


    【解决方案1】:

    我认为你可以这样使用它:

    long beginValue = NetworkInterface.GetIPv4Statistics().BytesReceived;
    DateTime beginTime = DateTime.Now;
    
    // do something
    
    long endValue = NetworkInterface.GetIPv4Statistics().BytesReceived;
    DateTime endTime = DateTime.Now;
    
    long recievedBytes = endValue - beginValue;
    double totalSeconds = (endTime - beginTime).TotalSeconds;
    
    var bytesPerSecond = recievedBytes / totalSeconds;
    

    定期更新的代码片段

    private object _lockObj;
    private long bytesPerSecond = 0;
    private Timer _refreshTimer = new Timer { Interval = 1000 };
    
    // do in ctor or some init method
    _refreshTimer.Tick += _refreshTimer_Tick;
    _refreshTimer.Enabled = true;
    
    private void _refreshTimer_Tick(object sender, EventArgs e)
    {
      ThreadPool.QueueUserItem(callback => 
      {
        long beginValue = NetworkInterface.GetIPv4Statistics().BytesReceived;
        DateTime beginTime = DateTime.Now;
    
        Thread.Sleep(1000);
    
        long endValue = NetworkInterface.GetIPv4Statistics().BytesReceived;
        DateTime endTime = DateTime.Now;
    
        long recievedBytes = endValue - beginValue;
        double totalSeconds = (endTime - beginTime).TotalSeconds;
    
        lock(_lockObj)
        {
          bytesPerSecond = recievedBytes / totalSeconds;
        }
      });
    
    }
    

    您可以将此与一些跟踪相结合,以记录一段时间内收到的字节数

    【讨论】:

    • 实际上,我想动态更新值,这不是我想要的解决方案。不过还是谢谢。
    • 谢谢。想要一些澄清。您已将计时器间隔设置为 1 秒。再次调用 Thread.Sleep(1000)。那么,在那里等待总共需要 2 秒吗? _lockObj 的目标是什么?
    • Thread.Sleep(1000) 是在开始和结束测量之间等待 1 秒。 Timer Tick 不会受到影响,因此您的刷新时间约为 1 秒。 LockObj 用于确保只有一次访问突然对变量进行了访问。抱歉英语不好 ;) ...这不是我的母语。
    • 无法完全了解_lockObj 无论如何它也可以在没有它的情况下工作。我正在使用它进行自己的修改。谢谢。
    • 另外,当线程进入睡眠状态时。我的用户界面正在冻结。那么,有什么解决办法吗?
    【解决方案2】:
    NetworkInterface.GetIPv4Statistics().BytesReceived 
    

    将显示给定接口接收到的总字节数。

    我认为您不能完全使用它来获取每秒接收的字节数。

    查看This

    【讨论】:

    • 你能推荐任何我可以使用的方法吗?
    • 如果你能得到网络接口的总 UP 时间,那么你可能想要这个:(NetworkInterface.GetIPv4Statistics().BytesReceived)/(UP time in seconds)
    【解决方案3】:

    http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipv4interfacestatistics.bytesreceived.aspx

    根据 MSDN(正如其他人也指出的那样)它获取在接口上接收到的字节数。

    例如,如果网络接口断开并重新连接(例如,网络电缆被拔出或无线连接断开),它将如何表现。

    如果您想要一种更可靠的方法来捕获数据包、过滤数据包、剖析数据包并只计算重要的数据包,请查看http://sourceforge.net/projects/sharppcap/

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 2021-02-03
      • 2013-11-24
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2014-07-08
      • 1970-01-01
      相关资源
      最近更新 更多