如何使用C#检测互联网何时闲置(无下载/上传),并在启用时启动下载?
答案 0 :(得分:2)
如果您正在等待没有连接的时刻......即使您认为自己没有使用互联网,也必须知道有很多连接。
尝试查看WireShark和Prcomon(来自系统管理员)以了解相关信息。
注意:如果您通过Mono在Mac或Linux上使用.NET,您应该知道这些API不能很好地移植到其他操作系统。所以,我在这里描述的仅适用于Windows。
如果您想了解流量,可以尝试使用System.Net.NetworkInformation.IPGlobalStatistics。
你可以这样做:
var properties = IPGlobalProperties.GetIPGlobalProperties();
// IPGlobalStatistics for IPv4
var ipv4stat = properties.GetIPv4GlobalStatistics();
// IPGlobalStatistics for IPv6
var ipv6stat = properties.GetIPv6GlobalStatistics();
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("");
如果您需要在互联网可用时收到通知,您可以订阅System.Net.NetworkInformation.NetworkChange。NetworkAvailabilityChanged。这样,如果互联网已连接或断开连接,您将收到通知事件(不要忘记取消订阅)。
示例:
var handler = new NetworkAddressChangedEventHandler
(
(sender, args) =>
{
//handle notification
}
);
System.Net.NetworkInformation.NetworkChange += handler;
// Unsubscribe:
System.Net.NetworkInformation.NetworkChange -= handler;
您可能有兴趣了解哪些网络适配器已启用或关闭,以及每个网络适配器的流量...具体如下所示。
让我们定义“空闲”。我会说“空闲”意味着互联网可用(上面检查),如果它没有在给定的大量时间内使用。
所以,你需要做的另一件事就是调用NetworkInterface.GetAllNetworkInterfaces,它将为你提供一个System.Net.NetworkInformation.NetworkInterface数组,你可以在其中调用方法GetIPStatistics来获取一个IPStatistics对象那特定的netowork界面。您还可以阅读OperationalStatus属性以了解特定接口是否已启用
示例:
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);
}
您需要做的是以查询方式存储此信息,以检查信息是否已更改:
// Fields
Dictionary<string, Tuple<long, long>> data
= new Dictionary<string, Tuple<long, long>>();
bool IsInternetIdle()
{
bool idle = true;
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in adapters)
{
var stats = adapter.GetIPStatistics();
Tuple<long, long> info;
if (!data.TryGetValue(adapter.Name, out info))
{
//New Adapter
info = new Tuple<long, long>
(
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;
}
并添加一些逻辑来处理空闲时间:
// 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;
}
}
使用示例:
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();
提醒
IsInternetIdle
(如上所述)所有网络适配器都是新的。在陈述使用之前,您可能希望先对GetInternetIdleTime
(如上所述)进行抢先调用。IsInternetIdle
和GetInternetIdleTime
仅在互联网可用时使用。您可以添加检查以查看各个网络适配器是否已启动。GetInternetIdleTime
的结果不是连接处于非活动状态的总时间,而是自发现连接处于非活动状态以来的时间。你可能想在一个计时器中调用GetInternetIdleTime
(如果你的应用程序有一个主循环 - 比如,它是一个游戏 - 你可以用给定的频率调用它)。由于这是针对Windows的,因此您可以尝试使用WMI来获取网络适配器信息,因为我会将您推荐给Mladen Prajdic的Find only physical network adapters with WMI Win32_NetworkAdapter class。
您可以使用PCapDotNet模拟WireShark的功能,您可以在CodeProject.com找到示例。让我DuckDuckGo that为你服务。