NetworkInterface.GetIPv4Statistics()。BytesReceived - 它返回什么?

时间:2012-11-27 07:44:44

标签: c# .net networking ip

该特定领域的回报是什么?我想要每秒接收的字节数。我应该依靠这个吗?

3 个答案:

答案 0 :(得分:8)

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

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 :(得分:3)

NetworkInterface.GetIPv4Statistics().BytesReceived 

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

我不认为你可以使用它来获得每秒接收的字节数。

检查This

答案 2 :(得分:0)

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

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

例如,如果网络接口断开连接并重新连接(例如拔出网络电缆或无线连接断开),它的行为如何。

如果你想要一种更可靠的方法来捕获数据包,过滤它们,解剖它们并只计算那些重要的数据包,那么看看http://sourceforge.net/projects/sharppcap/