C#中如何监测IPv6网速及流量-创新互联
创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!
成都创新互联公司专注于企业成都全网营销、网站重做改版、兴化网站定制设计、自适应品牌网站建设、H5场景定制、商城网站建设、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为兴化等各大城市提供网站开发制作服务。这篇文章主要讲解了C#中如何监测IPv6网速及流量,内容清晰明了,相信大家阅读完之后会有帮助。
1、前言
最近做项目需要用到监测网速及流量,我经过百度和墙内谷歌都没能快速发现监测IPV6流量和网速的用例;也经过自己的一番查询和调试,浪费了不少时间,现在作为经验分享出来希望大家指正。
2、C#代码
using System.Net.NetworkInformation; using System.Timers; namespace Monitor { public class MonitorNetwork { public string UpSpeed { get; set; } public string DownSpeed { get; set; } public string AllTraffic { get; set; } private string NetCardDescription { get; set; } //建立连接时上传的数据量 private long BaseTraffic { get; set; } private long OldUp { get; set; } private long OldDown { get; set; } private NetworkInterface networkInterface { get; set; } private Timer timer = new Timer() { Interval = 1000 }; public void Close() { timer.Stop(); } public MonitorNetwork(string netCardDescription) { timer.Elapsed += Timer_Elapsed; NetCardDescription = netCardDescription; timer.Interval = 1000; } public bool Start() { networkInterface = null; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var var in nics) { if (var.Description.Contains(NetCardDescription)) { networkInterface = var; break; } } if (networkInterface == null) { return false; } else { BaseTraffic = (networkInterface.GetIPStatistics().BytesSent + networkInterface.GetIPStatistics().BytesReceived); OldUp = networkInterface.GetIPStatistics().BytesSent; OldDown = networkInterface.GetIPStatistics().BytesReceived; timer.Start(); return true; } } private string[] units = new string[] {"KB/s","MB/s","GB/s" }; private void CalcUpSpeed() { long nowValue = networkInterface.GetIPStatistics().BytesSent; int num = 0; double value = (nowValue - OldUp) / 1024.0; while (value > 1023) { value = (value / 1024.0); num++; } UpSpeed = value.ToString("0.0") + units[num]; OldUp = nowValue; } private void CalcDownSpeed() { long nowValue = networkInterface.GetIPStatistics().BytesReceived; int num = 0; double value = (nowValue - OldDown) / 1024.0; while (value > 1023) { value = (value / 1024.0); num++; } DownSpeed = value.ToString("0.0") + units[num]; OldDown = nowValue; } private string[] unitAlls = new string[] { "KB", "MB", "GB" ,"TB"}; private void CalcAllTraffic() { long nowValue = OldDown+OldUp; int num = 0; double value = (nowValue- BaseTraffic) / 1024.0; while (value > 1023) { value = (value / 1024.0); num++; } AllTraffic = value.ToString("0.0") + unitAlls[num]; } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { CalcUpSpeed(); CalcDownSpeed(); CalcAllTraffic(); } } }
网站栏目:C#中如何监测IPv6网速及流量-创新互联
URL地址:http://myzitong.com/article/docpjs.html