获取网络下载和上传速度

时间:2014-02-23 21:01:15

标签: c#

我尝试获得网络下载和上传速度:

NetworkInterface[] nicArr = null;
IPv4InterfaceStatistics interfaceStats = null;

private void chartTimer_Tick(object sender, EventArgs e)
{            
        interfaceStats = nicArr[selectedIndex].GetIPv4Statistics();

        long bytesReceived = interfaceStats.BytesReceived;
        long bytesSent = interfaceStats.BytesSent;

        long CurrentBytesReceived = interfaceStats.BytesReceived;
        long CurrentBytesSent = interfaceStats.BytesSent;
        lblDownload2.Text = (CurrentBytesReceived - bytesReceived).ToString();
        lblUpload2.Text = ((CurrentBytesSent - bytesSent)).ToString();
}

我的问题是我的Download速度从517854开始,此数字仅提升和提升(与Upload速度相同),当没有流量时,此数字仍然保持不变高而不是零

2 个答案:

答案 0 :(得分:2)

这些属性包含发送和接收的金额,它会不断增加。

你需要获得一个初始值,然后在间隔轮询当前值并计算差异。

一个非常粗略的例子:

var base_value = interfaceStats.BytesReceived;

while (true) {
    var current_value = interfaceStats.BytesReceived;
    var diff = current_value - base_value;

    Console.WriteLine(diff + " bytes/sec");

    Thread.Sleep(1000);
}

答案 1 :(得分:1)

这些属性为您提供转移的总字节数,您需要的是该数字的derivative(变化率)。

最简单的方法就是做简单的数学问题

total2 - total1
---------------
 time2 - time1

所以你需要录音然后比较这两点以获得速度。

private long _lastBytesRecevied;
private long _lastBytesSent;
private DateTime _lastReceivedMesurement;
private DateTime _lastSentMesurement;

//This needs to be done once at the start of the class to "seed" the first value.
private Init()
{
    _lastReceivedMesurement = DateTime.UtcNow;
    _lastBytesRecevied = interfaceStats.BytesReceived;

    _lastSentMesurement = DateTime.UtcNow;
    _lastBytesSent = interfaceStats.BytesSent;
}

private double getKBDownloadSpeed()
{
    double result = (interfaceStats.BytesReceived - _lastBytesRecevied) / (DateTime.UtcNow - _lastMesurement).TotalSeconds;

    _lastReceivedMesurement = DateTime.UtcNow;
    _lastBytesRecevied = interfaceStats.BytesReceived;

    return result / 1024d;
}

private double getKBUploadSpeed()
{
    double result = (interfaceStats.BytesSent - _lastBytesSent) / (DateTime.UtcNow - _lastSentMesurement).TotalSeconds;

    _lastSentMesurement = DateTime.UtcNow;
    _lastBytesSent = interfaceStats.BytesSent;

    return result / 1024d;
}

现在,您的两个函数返回上次调用函数和当前调用之间的平均下载速度。