检测互联网连接是否繁忙

时间:2012-02-22 12:08:04

标签: c# .net language-agnostic network-utilization

我们正在开发一个将安装在PC上的应用程序,它将执行一些后台上传和下载到我们的服务器。其中一个要求是检测互联网连接当前是否正忙(比如高于50%利用率),如果是,则需要退回并尝试另一次。主要原因是确保应用程序在游戏,观看在线电影或积极下载文件时不会干扰用户体验

经过多次思考和研究谷歌,当然还有SO,我还没有找到一个如何实现这个的好方法,所以决定把它扔出去。 该应用程序在C#,.NET 4.0中实现,我正在寻找所有形式的响应 - 无论是在C#或其他语言中实现,伪逻辑还是如何实现的方法 - 测量互联网流量利用率本地PC具有足够高的准确性。

为了避免重复劳动,到目前为止,我已经尝试了这些(以及它们不适合的原因)

  • 使用WMI获取网络统计信息。大多数SO帖子和解决方案从那以后将其称为方法,但它不符合我们的要求,因为测量针对网络接口容量(例如1GB以太网卡)发送/接收的字节以便利用将为LAN流量提供良好的衡量标准但不适用于互联网流量(实际互联网带宽可能仅为8Mbps)
  • 使用.NET网络信息统计或性能计数器 - 产生与上述相似的读数因此具有相同的缺点
  • 使用ICMP(Ping)并测量RTT。有人建议400ms RTT被认为是繁忙网络的缓慢和良好的指示,但我被告知用户使用调制解调器(是的,我们必须支持),使用反向代理或微波链路经常得到ping,因此不是很好测量
  • 开始下载一个已知文件并测量速度 - 这本身会产生我们试图避免的流量,如果经常进行此检查,我们的应用程序最终会产生大量的互联网流量 - 这又不理想< / LI>
  • MOD:使用BITS - 可以在用户PC上禁用此服务,需要更改组策略并假设服务器为IIS(具有自定义配置),在我们的示例中,我们的服务器不是IIS

所以在这里,我很困惑并寻找一些建议。我突出了问题文本,以便你们不要迷失阅读本文,并想知道问题是什么。感谢。

3 个答案:

答案 0 :(得分:5)

您可以使用UPnP查询路由器,并检索通过网络发送和接收的字节数。您可以继续在路由器上检查此值以确定活动是什么。遗憾的是,此功能似乎没有详细记录,但可以在C#应用程序中实现UPnP通信功能。您将需要使用UDP来查询路由器(UPnP发现),一旦找到设备,查询其功能,然后使用WebClient(TCP)查询Internet网关设备发送和接收的数据包数。

Code for a UPnP library:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Xml;
using System.IO;
namespace UPNPLib
{
    public class RouterElement
    {
        public RouterElement()
        {
        }
        public override string ToString()
        {
            return Name;
        }
        public List children = new List();
        public RouterElement parent;
        public string Name;
        public string Value;
        public RouterElement this[string name] {
            get
            {
                foreach (RouterElement et in children)
                {
                    if (et.Name.ToLower().Contains(name.ToLower()))
                    {
                        return et;
                    }
                }
                foreach (RouterElement et in children)
                {
                    Console.WriteLine(et.Name);
                }
                throw new KeyNotFoundException("Unable to find the specified entry");
            }
    }
        public RouterElement(XmlNode node, RouterElement _parent)
        {

            Name = node.Name;
            if (node.ChildNodes.Count 
        /// Gets the root URL of the device
        /// 
        /// 
        public static string GetRootUrl()
        {
            StringBuilder mbuilder = new StringBuilder();
            mbuilder.Append("M-SEARCH * HTTP/1.1\r\n");
            mbuilder.Append("HOST: 239.255.255.250:1900\r\n");
            mbuilder.Append("ST:upnp:rootdevice\r\n");
            mbuilder.Append("MAN:\"ssdp:discover\"\r\n");
            mbuilder.Append("MX:3\r\n\r\n");
            UdpClient mclient = new UdpClient();
            byte[] dgram = Encoding.ASCII.GetBytes(mbuilder.ToString());
            mclient.Send(dgram,dgram.Length,new IPEndPoint(IPAddress.Broadcast,1900));
            IPEndPoint mpoint = new IPEndPoint(IPAddress.Any, 0);
            rootsearch:

            dgram = mclient.Receive(ref mpoint);
            string mret = Encoding.ASCII.GetString(dgram);
            string orig = mret;
            mret = mret.ToLower();
            string url = orig.Substring(mret.IndexOf("location:") + "location:".Length, mret.IndexOf("\r", mret.IndexOf("location:")) - (mret.IndexOf("location:") + "location:".Length));
            WebClient wclient = new WebClient();
            try
            {
                Console.WriteLine("POLL:" + url);
                string reply = wclient.DownloadString(url);

                if (!reply.ToLower().Contains("router"))
                {
                    goto rootsearch;
                }
            }
            catch (Exception)
            {
                goto rootsearch;
            }
            return url;
        }
        public static RouterElement enumRouterFunctions(string url)
        {

            XmlReader mreader = XmlReader.Create(url);
            XmlDocument md = new XmlDocument();
            md.Load(mreader);
            XmlNodeList rootnodes = md.GetElementsByTagName("serviceList");
            RouterElement elem = new RouterElement();
            foreach (XmlNode et in rootnodes)
            {
                RouterElement el = new RouterElement(et, null);
                elem.children.Add(el);
            }

            return elem;
        }
        public static RouterElement getRouterInformation(string url)
        {
            XmlReader mreader = XmlReader.Create(url);
            XmlDocument md = new XmlDocument();
            md.Load(mreader);
            XmlNodeList rootnodes = md.GetElementsByTagName("device");
            return new RouterElement(rootnodes[0], null);
        }

    }
    public class RouterMethod
    {
        string url;
        public string MethodName;
        string parentname;
        string MakeRequest(string URL, byte[] data, string[] headers)
        {
            Uri mri = new Uri(URL);
            TcpClient mclient = new TcpClient();
            mclient.Connect(mri.Host, mri.Port);
            Stream mstream = mclient.GetStream();
            StreamWriter textwriter = new StreamWriter(mstream);
            textwriter.Write("POST "+mri.PathAndQuery+" HTTP/1.1\r\n");

            textwriter.Write("Connection: Close\r\n");

            textwriter.Write("Content-Type: text/xml; charset=\"utf-8\"\r\n");

            foreach (string et in headers)
            {
                textwriter.Write(et + "\r\n");
            }
            textwriter.Write("Content-Length: " + (data.Length).ToString()+"\r\n");
            textwriter.Write("Host: " + mri.Host+":"+mri.Port+"\r\n");


            textwriter.Write("\r\n");
            textwriter.Flush();



            Stream reqstream = mstream;
            reqstream.Write(data, 0, data.Length);
            reqstream.Flush();
            StreamReader reader = new StreamReader(mstream);
            while (reader.ReadLine().Length > 2)
            {

            }
            return reader.ReadToEnd();
        }
        public RouterElement Invoke(string[] args)
        {

            MemoryStream mstream = new MemoryStream();
            StreamWriter mwriter = new StreamWriter(mstream);
            //TODO: Implement argument list
            string arglist = "";

            mwriter.Write("" + "" + "");


            mwriter.Write("");//" + arglist + "");
            mwriter.Write("");
            mwriter.Flush();

            List headers = new List();

            headers.Add("SOAPAction: \"" + parentschema + "#" + MethodName + "\"");

            mstream.Position = 0;
            byte[] dgram = new byte[mstream.Length];

            mstream.Read(dgram, 0, dgram.Length);

            XmlDocument mdoc = new XmlDocument();
            string txt = MakeRequest(url, dgram, headers.ToArray());
            mdoc.LoadXml(txt);
            try
            {
                RouterElement elem = new RouterElement(mdoc.ChildNodes[0], null);

                return elem["Body"].children[0];
            }
            catch (Exception er)
            {
                RouterElement elem = new RouterElement(mdoc.ChildNodes[1], null);
                return elem["Body"].children[0];
            }

        }
        public List parameters = new List();
        string baseurl;
        string parentschema;
        public RouterMethod(string svcurl, RouterElement element,string pname, string baseURL, string svcpdsc)
        {
            parentschema = svcpdsc;
            baseurl = baseURL;
            parentname = pname;
            url = svcurl;
            MethodName = element["name"].Value;
            try
            {
                foreach (RouterElement et in element["argumentList"].children)
                {
                    parameters.Add(et.children[0].Value);
                }
            }
            catch (KeyNotFoundException)
            {
            }
        }
    }
    public class RouterService
    {
        string url;
        public string ServiceName;
        public List methods = new List();
        public RouterMethod GetMethodByNonCaseSensitiveName(string name)
        {
            foreach (RouterMethod et in methods)
            {
                if (et.MethodName.ToLower() == name.ToLower())
                {
                    return et;
                }
            }
            throw new KeyNotFoundException();
        }
        public RouterService(RouterElement element, string baseurl)
        {

            ServiceName = element["serviceId"].Value;
            url = element["controlURL"].Value;

            WebClient mclient = new WebClient();
            string turtle = element["SCPDURL"].Value;
            if (!turtle.ToLower().Contains("http"))
            {
                turtle = baseurl + turtle;
            }
            Console.WriteLine("service URL " + turtle);
            string axml = mclient.DownloadString(turtle);
            XmlDocument mdoc = new XmlDocument();
            if (!url.ToLower().Contains("http"))
            {
                url = baseurl + url;
            }
            mdoc.LoadXml(axml);
            XmlNode mainnode = mdoc.GetElementsByTagName("actionList")[0];
            RouterElement actions = new RouterElement(mainnode, null);
            foreach (RouterElement et in actions.children)
            {
                RouterMethod method = new RouterMethod(url, et,ServiceName,baseurl,element["serviceType"].Value);
                methods.Add(method);
            }

        }
    }
}



Code for a bandwidth meter:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UPNPLib;
using System.IO;

namespace bandwidthmeter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            BinaryReader mreader = new BinaryReader(File.Open("bandwidthlog.txt", FileMode.OpenOrCreate));
            if (mreader.BaseStream.Length > 0)
            {
                prevsent = mreader.ReadInt64();
                prevrecv = mreader.ReadInt64();
            }
            mreader.Close();
            List services = new List();
            string fullurl = UPNP.GetRootUrl();
            RouterElement router = UPNP.enumRouterFunctions(fullurl);
            Console.WriteLine("Router feature enumeration complete");
            foreach (RouterElement et in router.children)
            {

                services.Add(new RouterService(et.children[0], fullurl.Substring(0, fullurl.IndexOf("/", "http://".Length+1))));
            }
            getReceiveDelegate = services[1].GetMethodByNonCaseSensitiveName("GetTotalBytesReceived");
            getSentDelegate = services[1].GetMethodByNonCaseSensitiveName("GetTotalBytesSent");
            Console.WriteLine("Invoking " + getReceiveDelegate.MethodName);
            //Console.WriteLine(services[1].GetMethodByNonCaseSensitiveName("GetTotalPacketsSent").Invoke(null));

            Timer mymer = new Timer();
            mymer.Tick += new EventHandler(mymer_Tick);
            mymer.Interval = 1000;
            mymer.Start();
            FormClosed += new FormClosedEventHandler(Form1_FormClosed);
        }
        long prevsent = 0;
        long prevrecv = 0;
        void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            BinaryWriter mwriter = new BinaryWriter(File.Open("bandwidthlog.txt", FileMode.OpenOrCreate));
            mwriter.Write(getsent());
            mwriter.Write(getreceived());
            mwriter.Flush();
            mwriter.Close();

        }
        long getsent()
        {
            long retval = Convert.ToInt64(getSentDelegate.Invoke(null).children[0].Value);
            if (prevsent > retval)
            {
                retval = prevsent + retval;
            }
            return retval;
        }
        long getreceived()
        {
            long retval = Convert.ToInt64(getReceiveDelegate.Invoke(null).children[0].Value);
            if (prevrecv > retval)
            {
                retval = prevrecv + retval;
            }
            return retval;
        }
        void mymer_Tick(object sender, EventArgs e)
        {
            label1.Text = "Sent: "+(getsent()/1024/1024).ToString()+"MB\nReceived: "+(getreceived()/1024/1024).ToString()+"MB";

        }
        RouterMethod getSentDelegate;
        RouterMethod getReceiveDelegate;

    }
}

答案 1 :(得分:4)

您是否考虑过使用Background Intelligent Transfer Service (BITS)。它已经设计用于完成这项工作:

  

后台智能传输服务(BITS)在客户端和服务器之间传输文件(下载或上传),并提供与传输相关的进度信息。您也可以从同行下载文件。

  

保留其他网络应用程序的响应能力。

我不确定它是否有托管接口(我可以看到对Powershell Cmdlet的引用),因此您可能必须使用COM互操作才能使用它。

答案 2 :(得分:1)

假设您正在瞄准Windows PC(正如您所说的使用C#进行开发),您是否看过后台智能传输服务BITS

有一些例子说明如何在MSDN和其他地方使用C#挂钩,例如: http://msdn.microsoft.com/en-us/magazine/cc188766.aspx