Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are waiting for a moment where there are no connections... you have to know that there are a lot of connections even when you think you are not using Internet.</p> <p>Try giving a look at <a href="https://www.wireshark.org/" rel="nofollow">WireShark</a> and <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow">Prcomon</a> (from sysitnerals) to have an idea.</p> <hr> <h2>Notwork traffic</h2> <p><em>Note:</em> if you are using .NET on Mac or Linux via Mono, you should know that this APIs don't port well to other operating systems. So, what I describe here is only for Windows.</p> <p>If what you want is to have an idea of the traffic, you can try using <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipglobalstatistics.aspx" rel="nofollow">System.Net.NetworkInformation.IPGlobalStatistics</a>.</p> <p>You can do so, like this:</p> <pre><code>var properties = IPGlobalProperties.GetIPGlobalProperties(); // IPGlobalStatistics for IPv4 var ipv4stat = properties.GetIPv4GlobalStatistics(); // IPGlobalStatistics for IPv6 var ipv6stat = properties.GetIPv6GlobalStatistics(); </code></pre> <p>From the <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipglobalstatistics.aspx#code-snippet-2" rel="nofollow">example at MSDN</a>:</p> <pre><code>Console.WriteLine(" Forwarding enabled ...................... : {0}", ipstat.ForwardingEnabled); Console.WriteLine(" Interfaces .............................. : {0}", ipstat.NumberOfInterfaces); Console.WriteLine(" IP addresses ............................ : {0}", ipstat.NumberOfIPAddresses); Console.WriteLine(" Routes .................................. : {0}", ipstat.NumberOfRoutes); Console.WriteLine(" Default TTL ............................. : {0}", ipstat.DefaultTtl); Console.WriteLine(""); Console.WriteLine(" Inbound Packet Data:"); Console.WriteLine(" Received ............................ : {0}", ipstat.ReceivedPackets); Console.WriteLine(" Forwarded ........................... : {0}", ipstat.ReceivedPacketsForwarded); Console.WriteLine(" Delivered ........................... : {0}", ipstat.ReceivedPacketsDelivered); Console.WriteLine(" Discarded ........................... : {0}", ipstat.ReceivedPacketsDiscarded); Console.WriteLine(" Header Errors ....................... : {0}", ipstat.ReceivedPacketsWithHeadersErrors); Console.WriteLine(" Address Errors ...................... : {0}", ipstat.ReceivedPacketsWithAddressErrors); Console.WriteLine(" Unknown Protocol Errors ............. : {0}", ipstat.ReceivedPacketsWithUnknownProtocol); Console.WriteLine(""); Console.WriteLine(" Outbound Packet Data:"); Console.WriteLine(" Requested ........................... : {0}", ipstat.OutputPacketRequests); Console.WriteLine(" Discarded ........................... : {0}", ipstat.OutputPacketsDiscarded); Console.WriteLine(" No Routing Discards ................. : {0}", ipstat.OutputPacketsWithNoRoute); Console.WriteLine(" Routing Entry Discards .............. : {0}", ipstat.OutputPacketRoutingDiscards); Console.WriteLine(""); Console.WriteLine(" Reassembly Data:"); Console.WriteLine(" Reassembly Timeout .................. : {0}", ipstat.PacketReassemblyTimeout); Console.WriteLine(" Reassemblies Required ............... : {0}", ipstat.PacketReassembliesRequired); Console.WriteLine(" Packets Reassembled ................. : {0}", ipstat.PacketsReassembled); Console.WriteLine(" Packets Fragmented .................. : {0}", ipstat.PacketsFragmented); Console.WriteLine(" Fragment Failures ................... : {0}", ipstat.PacketFragmentFailures); Console.WriteLine(""); </code></pre> <hr> <h2>Is Internet Available?</h2> <p>If you need to get a notification when the Internet is avaliable, you can subscribe to <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.aspx" rel="nofollow">System.Net.NetworkInformation.NetworkChange</a>.<a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx" rel="nofollow">NetworkAvailabilityChanged</a>. That way you will get a notification event if the Internet is connected or disconnected (Don't forget to unsubscribe).</p> <p>Example:</p> <pre><code>var handler = new NetworkAddressChangedEventHandler ( (sender, args) =&gt; { //handle notification } ); System.Net.NetworkInformation.NetworkChange += handler; // Unsubscribe: System.Net.NetworkInformation.NetworkChange -= handler; </code></pre> <p>You may be interested in knowing what Network adapters are Up or Down and how much traffic each one has... for that see below.</p> <hr> <h2>Idle &amp; Idle time</h2> <p>Let's define "<em>Idle</em>". I would say "Idle" means that the Internet is available (check above), and if it hasn't been used for a given ammount of time.</p> <p>So, the other thing you got to do is is calling <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces%28v=vs.110%29.aspx" rel="nofollow">NetworkInterface.GetAllNetworkInterfaces</a> that will give you an array of <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface%28v=vs.110%29.aspx" rel="nofollow">System.Net.NetworkInformation.NetworkInterface</a> on which you can call the method <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getipstatistics%28v=vs.110%29.aspx" rel="nofollow">GetIPStatistics</a> to get an IPStatistics object for that particular netowork interface. You can also read the <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.operationalstatus%28v=vs.110%29.aspx" rel="nofollow">OperationalStatus</a> property to know if the particular interface is Up or not</p> <p>Example:</p> <pre><code> NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (var adapter in adapters) { // Is Up, Down, something else? Console.WriteLine(" {0} is {1}", adapter.Name, dapter.OperationalStatus); var stats = adapter.GetIPStatistics(); // Read some properties Console.WriteLine(" Bytes Recieved: {0}", stats.BytesReceived); Console.WriteLine(" Bytes Sent: {0}", stats.BytesSent); } </code></pre> <p>What you will need to do is store this information in a way you can query it, to check if it has changed:</p> <pre><code>// Fields Dictionary&lt;string, Tuple&lt;long, long&gt;&gt; data = new Dictionary&lt;string, Tuple&lt;long, long&gt;&gt;(); bool IsInternetIdle() { bool idle = true; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (var adapter in adapters) { var stats = adapter.GetIPStatistics(); Tuple&lt;long, long&gt; info; if (!data.TryGetValue(adapter.Name, out info)) { //New Adapter info = new Tuple&lt;long, long&gt; ( stats .BytesReceived, stats .BytesSent ); data.Add(adapter.Name, info); } else { if ( info.Item1 != stats .BytesReceived || info.Item2 != stats .BytesSent ) { idle = false; break; } } } //Console.WriteLine("Is Idle: {0}", idle.ToString()); return idle; } </code></pre> <p>And add some logic to handle idle time:</p> <pre><code>// Fields Stopwatch watch = new Stopwatch(); static TimeSpan? GetInternetIdleTime() { if (IsInternetIdle()) { if (!watch.IsRunning) { watch.Start(); } //Console.WriteLine("Idle Time: {0}", XmlConvert.ToString(watch.Elapsed)); return watch.Elapsed; } else { watch.Stop(); watch.Reset(); return null; } } </code></pre> <p>Example usage:</p> <pre><code>GetInternetIdleTime(); //preemptive call Thread.Sleep(1000); var result = GetInternetIdleTime(); if (result.HasValue) { Console.WriteLine("Idle time: {0}", result.Value); } else { Console.WriteLine("Not Idle"); } Console.ReadKey(); </code></pre> <hr> <p><strong>Words of caution</strong></p> <ol> <li>Remember to unsubscribe your event handler.</li> <li>This is intended to work on Windows only.</li> <li>Remember that the first run of <code>IsInternetIdle</code> (described above) all the network adapters are new. You may want to do a preemptive call to <code>GetInternetIdleTime</code> (described above) before stating using them.</li> <li>The methods <code>IsInternetIdle</code> and <code>GetInternetIdleTime</code> are intended to be used only when Internet is available. You could add checks to see if the individual network adapters are Up.</li> <li>The result of <code>GetInternetIdleTime</code> described above is not the total time that the connections has been inactive, but the time since it was discovered that the connections are inactive. You may want to call <code>GetInternetIdleTime</code> in a timer (of if your application has a main loop - say, it's a game - you can call it with a given frequency).</li> <li>If a netwokr adaptes is Active, it doesn't mean that it is using <em>Internet</em>. Maybe it is connected to some <em>Intranet</em>. There is no way to tell if "Internet" is reachable. You should check for conectivity with individual servers yourself. Don't know what to check? It can be problematic because DNS can be overrrided locally... but you can try <a href="http://example.org/" rel="nofollow">example.or</a>, <a href="http://internic.net" rel="nofollow">InterNIC.net</a> or even <a href="http://www.ntp.org/" rel="nofollow">ntp.ord</a>.</li> </ol> <hr> <h2>Alternative</h2> <p>Since this is for Windows anyway, you can try using <a href="http://msdn.microsoft.com/en-us/library/aa394595%28v=vs.85%29.aspx" rel="nofollow">WMI</a> to the network adapters information, for that I'll refer you to <a href="http://weblogs.sqlteam.com/mladenp/archive/2010/11/04/find-only-physical-network-adapters-with-wmi-win32_networkadapter-class.aspx" rel="nofollow">Find only physical network adapters with WMI Win32_NetworkAdapter class</a> by Mladen Prajdic.</p> <hr> <h2>Digging deeper</h2> <p>You can emulate what WireShark does by using <a href="https://pcapdotnet.codeplex.com/" rel="nofollow">PCapDotNet</a>, you will find examples at <a href="http://codeproject.com" rel="nofollow">CodeProject.com</a>. Let me <a href="https://lmddgtfy.net/?q=C%23+winpcap+site%3Acodeproject.com" rel="nofollow">DuckDuckGo that</a> for you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload