// 实时网速 - 绿色工具箱 // C# 5.0 语法,零依赖。读网卡计数器算实时上下行速度,不发起任何测速请求(不跑流量) using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Net.NetworkInformation; using System.Windows.Forms; namespace GreenToolbox { // ===== 纯函数区(可自测) ===== public static class NetOps { // 速度文案:B/s → KB/s → MB/s。保留一位小数就够看,别整成 12.3456 MB/s public static string FormatSpeed(double bytesPerSec) { if (bytesPerSec < 0) bytesPerSec = 0; if (bytesPerSec < 1024) return ((long)bytesPerSec).ToString(CultureInfo.InvariantCulture) + " B/s"; double kb = bytesPerSec / 1024.0; if (kb < 1024) return string.Format(CultureInfo.InvariantCulture, "{0:0.0} KB/s", kb); double mb = kb / 1024.0; if (mb < 1024) return string.Format(CultureInfo.InvariantCulture, "{0:0.00} MB/s", mb); return string.Format(CultureInfo.InvariantCulture, "{0:0.00} GB/s", mb / 1024.0); } public static string FormatBytes(long bytes) { if (bytes < 0) bytes = 0; if (bytes < 1024) return bytes.ToString(CultureInfo.InvariantCulture) + " B"; double kb = bytes / 1024.0; if (kb < 1024) return string.Format(CultureInfo.InvariantCulture, "{0:0.0} KB", kb); double mb = kb / 1024.0; if (mb < 1024) return string.Format(CultureInfo.InvariantCulture, "{0:0.00} MB", mb); return string.Format(CultureInfo.InvariantCulture, "{0:0.00} GB", mb / 1024.0); } // 计数器会重置(网卡重连、系统重启)或读数为负,别让界面出现 -3 GB/s public static long SafeDelta(long now, long prev) { if (now < prev) return 0; return now - prev; } // 回环/隧道不算真实流量,统计进去会虚高 public static bool ShouldCount(NetworkInterfaceType type, OperationalStatus status) { if (status != OperationalStatus.Up) return false; if (type == NetworkInterfaceType.Loopback) return false; if (type == NetworkInterfaceType.Tunnel) return false; return true; } // 按字节速度给出「大概能干什么」的人话提示,比数字直观 public static string HintText(double downBytesPerSec) { if (downBytesPerSec < 1024) return "基本空闲"; if (downBytesPerSec < 100 * 1024) return "看网页、聊消息够用"; if (downBytesPerSec < 1024 * 1024) return "在线视频不卡"; if (downBytesPerSec < 8 * 1024 * 1024) return "高清视频 / 快速下载"; return "千兆级别的下载速度"; } // 汇总所有有效网卡的瞬时速度 public static void SumSpeed(List downDeltas, List upDeltas, out long down, out long up) { down = 0; up = 0; if (downDeltas != null) for (int i = 0; i < downDeltas.Count; i++) down += downDeltas[i]; if (upDeltas != null) for (int i = 0; i < upDeltas.Count; i++) up += upDeltas[i]; } // 网卡名太长会撑爆列表,截断加省略号 public static string Shorten(string name, int max) { if (name == null) return ""; if (max < 4 || name.Length <= max) return name; return name.Substring(0, max - 1) + "…"; } public static string SpeedSummary(long downPerSec, long upPerSec) { return "↓ " + FormatSpeed(downPerSec) + " ↑ " + FormatSpeed(upPerSec); } } public class NetForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private static readonly Color COL_LINE = Color.FromArgb(226, 232, 228); private Label lblDown, lblUp, lblHint, lblTotal; private ListView list; private CheckBox chkTop; private Timer timer; private Dictionary lastRx = new Dictionary(); private Dictionary lastTx = new Dictionary(); private long totalDown, totalUp; public NetForm() { InitUi(); timer = new Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(Tick); timer.Start(); Tick(null, null); } private void InitUi() { this.Text = "实时网速 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(560, 380); this.MinimumSize = new Size(500, 340); this.StartPosition = FormStartPosition.CenterScreen; int x = 18, y = 14; Label l0 = new Label(); l0.Text = "读网卡计数器显示实时上下行,不发起测速请求、不跑流量。"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 32; lblDown = new Label(); lblDown.Text = "↓ 0 B/s"; lblDown.AutoSize = true; lblDown.Font = new Font("Consolas", 24f, FontStyle.Bold); lblDown.ForeColor = COL_GREEN; lblDown.Location = new Point(x, y); this.Controls.Add(lblDown); lblUp = new Label(); lblUp.Text = "↑ 0 B/s"; lblUp.AutoSize = true; lblUp.Font = new Font("Consolas", 15f); lblUp.ForeColor = Color.FromArgb(90, 140, 175); lblUp.Location = new Point(x + 300, y + 12); this.Controls.Add(lblUp); y += 48; lblHint = new Label(); lblHint.Text = ""; lblHint.AutoSize = true; lblHint.ForeColor = COL_GRAY; lblHint.Location = new Point(x, y); this.Controls.Add(lblHint); y += 28; lblTotal = new Label(); lblTotal.Text = ""; lblTotal.AutoSize = true; lblTotal.ForeColor = Color.FromArgb(60, 68, 64); lblTotal.Location = new Point(x, y); this.Controls.Add(lblTotal); y += 30; chkTop = new CheckBox(); chkTop.Text = "窗口置顶(边下边看)"; chkTop.AutoSize = true; chkTop.Location = new Point(x, y); chkTop.ForeColor = Color.FromArgb(60, 68, 64); chkTop.CheckedChanged += delegate { this.TopMost = chkTop.Checked; }; this.Controls.Add(chkTop); y += 32; list = new ListView(); list.View = View.Details; list.FullRowSelect = true; list.Location = new Point(x, y); list.Size = new Size(524, 180); list.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; list.Columns.Add("网卡", 210); list.Columns.Add("下行", 120); list.Columns.Add("上行", 120); list.Columns.Add("累计", 120); this.Controls.Add(list); } private void Tick(object sender, EventArgs e) { long downSum = 0, upSum = 0; list.BeginUpdate(); try { list.Items.Clear(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0; i < nics.Length; i++) { NetworkInterface nic = nics[i]; try { if (!NetOps.ShouldCount(nic.NetworkInterfaceType, nic.OperationalStatus)) continue; IPv4InterfaceStatistics st = nic.GetIPv4Statistics(); long rx = st.BytesReceived; long tx = st.BytesSent; string key = nic.Id; long prx = lastRx.ContainsKey(key) ? lastRx[key] : rx; long ptx = lastTx.ContainsKey(key) ? lastTx[key] : tx; long drx = NetOps.SafeDelta(rx, prx); long dtx = NetOps.SafeDelta(tx, ptx); lastRx[key] = rx; lastTx[key] = tx; downSum += drx; upSum += dtx; ListViewItem row = new ListViewItem(NetOps.Shorten(nic.Name, 28)); row.SubItems.Add(NetOps.FormatSpeed(drx)); row.SubItems.Add(NetOps.FormatSpeed(dtx)); row.SubItems.Add(NetOps.FormatBytes(rx + tx)); list.Items.Add(row); } catch { } } } finally { list.EndUpdate(); } totalDown += downSum; totalUp += upSum; lblDown.Text = "↓ " + NetOps.FormatSpeed(downSum); lblUp.Text = "↑ " + NetOps.FormatSpeed(upSum); lblHint.Text = NetOps.HintText(downSum); lblTotal.Text = "本次已收 " + NetOps.FormatBytes(totalDown) + " · 已发 " + NetOps.FormatBytes(totalUp); } } public static class NetSelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static string Esc(string s) { if (s == null) return ""; return s.Replace("\r", "\\r").Replace("\n", "\\n"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } private static void CheckTrue(string name, bool ok, string detail) { Check(name, ok ? "yes" : "no", "yes"); if (!ok && detail != null) _lines.Add(" 详情:" + Esc(detail)); } public static int Run(string dir) { try { _lines.Add("实时网速 自测"); // ── 速度文案 ── Check("0 B/s", NetOps.FormatSpeed(0), "0 B/s"); Check("512 B/s", NetOps.FormatSpeed(512), "512 B/s"); Check("1023 B/s 还是 B", NetOps.FormatSpeed(1023), "1023 B/s"); Check("1024 B/s 变 KB", NetOps.FormatSpeed(1024), "1.0 KB/s"); Check("1.5 KB/s", NetOps.FormatSpeed(1536), "1.5 KB/s"); Check("1 MB/s", NetOps.FormatSpeed(1024 * 1024), "1.00 MB/s"); Check("12.5 MB/s", NetOps.FormatSpeed(12.5 * 1024 * 1024), "12.50 MB/s"); Check("1 GB/s", NetOps.FormatSpeed(1024.0 * 1024 * 1024), "1.00 GB/s"); Check("负数归零(计数器异常不至于显示 -1 KB/s)", NetOps.FormatSpeed(-5000), "0 B/s"); // ── 累计字节文案 ── Check("0 字节", NetOps.FormatBytes(0), "0 B"); Check("900 字节", NetOps.FormatBytes(900), "900 B"); Check("2 KB", NetOps.FormatBytes(2048), "2.0 KB"); Check("3 MB", NetOps.FormatBytes(3 * 1024 * 1024), "3.00 MB"); Check("2 GB", NetOps.FormatBytes(2L * 1024 * 1024 * 1024), "2.00 GB"); Check("负数归零", NetOps.FormatBytes(-1), "0 B"); // ── 增量:计数器回绕不能变成天文数字 ── Check("正常增量", NetOps.SafeDelta(1000, 400).ToString(), "600"); Check("计数器重置(now < prev)返回 0", NetOps.SafeDelta(100, 5000).ToString(), "0"); Check("相等返回 0", NetOps.SafeDelta(700, 700).ToString(), "0"); Check("超大值不溢出成负数", NetOps.SafeDelta(long.MaxValue, 0).ToString(), long.MaxValue.ToString()); // ── 网卡过滤 ── CheckTrue("回环不算流量", !NetOps.ShouldCount(NetworkInterfaceType.Loopback, OperationalStatus.Up), null); CheckTrue("隧道不算流量", !NetOps.ShouldCount(NetworkInterfaceType.Tunnel, OperationalStatus.Up), null); CheckTrue("断开的不算", !NetOps.ShouldCount(NetworkInterfaceType.Ethernet, OperationalStatus.Down), null); CheckTrue("以太网 Up 要算", NetOps.ShouldCount(NetworkInterfaceType.Ethernet, OperationalStatus.Up), null); CheckTrue("Wi-Fi Up 要算", NetOps.ShouldCount(NetworkInterfaceType.Wireless80211, OperationalStatus.Up), null); // ── 汇总 ── List d = new List(); List u = new List(); d.Add(1000); d.Add(2000); u.Add(100); u.Add(200); long down, up; NetOps.SumSpeed(d, u, out down, out up); Check("下行求和", down.ToString(), "3000"); Check("上行求和", up.ToString(), "300"); NetOps.SumSpeed(new List(), new List(), out down, out up); Check("空列表求和为 0", down + "/" + up, "0/0"); NetOps.SumSpeed(null, null, out down, out up); Check("null 不崩", down + "/" + up, "0/0"); // ── 文案 ── Check("空闲提示", NetOps.HintText(0), "基本空闲"); Check("网页级", NetOps.HintText(50 * 1024), "看网页、聊消息够用"); Check("在线视频级", NetOps.HintText(500 * 1024), "在线视频不卡"); Check("高清级", NetOps.HintText(4 * 1024 * 1024), "高清视频 / 快速下载"); Check("千兆级", NetOps.HintText(50 * 1024 * 1024), "千兆级别的下载速度"); Check("合并文案", NetOps.SpeedSummary(1024, 512), "↓ 1.0 KB/s ↑ 512 B/s"); // ── 名称截断 ── Check("短名不动", NetOps.Shorten("以太网", 10), "以太网"); Check("长名截断加省略号", NetOps.Shorten("一二三四五六七八九十", 5), "一二三四…"); Check("null 变空串", NetOps.Shorten(null, 5), ""); Check("max 太小不切", NetOps.Shorten("abcdef", 2), "abcdef"); // ── 真实机器上必须能枚举到网卡(否则工具等于白做)── NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); CheckTrue("能读到本机网卡列表", nics != null && nics.Length > 0, nics == null ? "null" : nics.Length.ToString()); int usable = 0; for (int i = 0; i < nics.Length; i++) { if (!NetOps.ShouldCount(nics[i].NetworkInterfaceType, nics[i].OperationalStatus)) continue; usable++; try { IPv4InterfaceStatistics st = nics[i].GetIPv4Statistics(); CheckTrue("网卡「" + NetOps.Shorten(nics[i].Name, 12) + "」能读计数器", st.BytesReceived >= 0 && st.BytesSent >= 0, null); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 读计数器异常:" + ex.GetType().Name); } } CheckTrue("至少有一块可统计的网卡(离线环境也算失败)", usable > 0, "usable=" + usable); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { System.IO.File.WriteAllText( System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "selftest-netspeed.txt"), all, new System.Text.UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } public static class NetProgram { [STAThread] public static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(NetSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new NetForm()); } } }