当前位置:首页 > 行业动态 > 正文

如何在C中实时获取当前网络速度?

在C#中获取当前网络速度可通过监控网络接口的数据流量实现,利用NetworkInterface类读取网卡收发字节数,定时计算两次采样间数据量差值,结合时间间隔换算为实时速率(如KB/s或Mbps),注意筛选有效网络接口并处理单位转换。

实现原理

网络速度的本质是单位时间内传输的数据量,通过以下步骤实现动态计算:

  1. 获取网络接口:选择活跃的物理网卡(排除虚拟或禁用的设备)。
  2. 记录初始流量值:保存当前接收和发送的总字节数。
  3. 定时采样与差值计算:通过计时器定期获取最新流量数据,计算时间差内的流量变化。
  4. 单位转换:将字节转换为KB、MB等易读单位。

代码实现

using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Threading;
public class NetworkSpeedMonitor
{
    private NetworkInterface _activeInterface;
    private long _previousBytesReceived;
    private long _previousBytesSent;
    private Stopwatch _stopwatch;
    public NetworkSpeedMonitor()
    {
        // 获取第一个活跃的有线或无线网卡
        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up &&
                (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                 nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211))
            {
                _activeInterface = nic;
                break;
            }
        }
        if (_activeInterface == null)
            throw new InvalidOperationException("未找到可用网络接口");
        _stopwatch = new Stopwatch();
        _previousBytesReceived = _activeInterface.GetIPv4Statistics().BytesReceived;
        _previousBytesSent = _activeInterface.GetIPv4Statistics().BytesSent;
        _stopwatch.Start();
    }
    // 获取当前速度(单位:KB/s)
    public (double downloadSpeed, double uploadSpeed) GetCurrentSpeed()
    {
        long currentReceived = _activeInterface.GetIPv4Statistics().BytesReceived;
        long currentSent = _activeInterface.GetIPv4Statistics().BytesSent;
        double elapsedSeconds = _stopwatch.Elapsed.TotalSeconds;
        double downloadSpeed = (currentReceived - _previousBytesReceived) / elapsedSeconds / 1024;
        double uploadSpeed = (currentSent - _previousBytesSent) / elapsedSeconds / 1024;
        // 重置计数器和计时器
        _previousBytesReceived = currentReceived;
        _previousBytesSent = currentSent;
        _stopwatch.Restart();
        return (downloadSpeed, uploadSpeed);
    }
}

使用示例

public class Program
{
    public static void Main()
    {
        try
        {
            NetworkSpeedMonitor monitor = new NetworkSpeedMonitor();
            while (true)
            {
                var speeds = monitor.GetCurrentSpeed();
                Console.WriteLine($"下载速度:{speeds.downloadSpeed:F2} KB/s | 上传速度:{speeds.uploadSpeed:F2} KB/s");
                Thread.Sleep(1000); // 每秒刷新一次
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误:{ex.Message}");
        }
    }
}

优化与注意事项

  1. 多网卡处理
    若设备存在多个活跃接口(如同时连接有线/无线),需遍历NetworkInterface集合,允许用户选择目标网卡。

  2. 时间间隔选择
    采样间隔过短(如100ms)可能导致数据波动,建议1-2秒平衡实时性与准确性。

    如何在C中实时获取当前网络速度?  第1张

  3. 单位扩展
    按需转换单位(如MB/s):

    double downloadSpeedMB = downloadSpeed / 1024; // 转换为MB/s
  4. 异常处理

    • 检查网卡是否突然断开。
    • 捕获NetworkInformationException权限错误(需管理员权限获取部分数据)。
  5. 性能优化
    在GUI应用中,使用后台线程或async/await避免界面卡顿。


常见问题

  • Q:结果与任务管理器显示不一致?
    A:系统统计包含所有进程流量,而代码仅监测当前接口总量,可能因其他程序占用导致差异。

  • Q:虚拟网卡干扰统计?
    A:通过NetworkInterfaceType过滤物理设备(如排除VirtualLoopback类型)。

  • Q:如何支持IPv6?
    A:改用GetIPStatistics()方法替代GetIPv4Statistics()


引用说明

本文代码基于以下官方文档实现:

  • Microsoft NetworkInterface Class
  • Stopwatch计时精度说明
0