在。net中检查Internet连接的最快和最有效的方法是什么?
当前回答
我个人觉得Anton和moffeltje的答案最好,但我增加了一个检查,排除VMWare和其他公司设置的虚拟网络。
public static bool IsAvailableNetworkActive()
{
// only recognizes changes related to Internet adapters
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) return false;
// however, this will include all adapters -- filter by opstatus and activity
NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
return (from face in interfaces
where face.OperationalStatus == OperationalStatus.Up
where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
where (!(face.Name.ToLower().Contains("virtual") || face.Description.ToLower().Contains("virtual")))
select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
}
其他回答
简介
在某些情况下,您需要在windows应用程序中使用c#代码检查internet是否可用。可能是在windows窗体中使用internet下载或上传文件,或从远程位置的数据库中获取一些数据,在这些情况下,internet检查是强制性的。
有一些方法可以从后面的代码中使用c#检查internet的可用性。这里解释了所有这些方法,包括它们的局限性。
InternetGetConnectedState(经由wininet)
“wininet”API可以用来检查本地系统是否有活跃的互联网连接。用于此操作的命名空间是'System.Runtime。并使用DllImport导入dll' wininet.dll'。在此之后,创建一个带有extern static的布尔变量,函数名为InternetGetConnectedState,带有两个参数描述和reservedValue,如示例所示。
注意:extern修饰符用于声明外部实现的方法。当您使用Interop服务调用非托管代码时,extern修饰符的常见用法是与DllImport属性一起使用。在这种情况下,方法也必须声明为静态的。
接下来创建一个名称为“IsInternetAvailable”的布尔方法。的 上面的函数将用于这个返回Internet的方法 本地系统状态
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int description, int reservedValue);
public static bool IsInternetAvailable()
{
try
{
int description;
return InternetGetConnectedState(out description, 0);
}
catch (Exception ex)
{
return false;
}
}
GetIsNetworkAvailable
下面的示例使用GetIsNetworkAvailable方法来确定网络连接是否可用。
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
System.Windows.MessageBox.Show("This computer is connected to the internet");
}
else
{
System.Windows.MessageBox.Show("This computer is not connected to the internet");
}
备注(根据MSDN):如果任何网络接口被标记为“向上”且不是环回或隧道接口,则网络连接被认为是可用的。
There are many cases in which a device or computer is not connected to a useful network but is still considered available and GetIsNetworkAvailable will return true. For example, if the device running the application is connected to a wireless network that requires a proxy, but the proxy is not set, GetIsNetworkAvailable will return true. Another example of when GetIsNetworkAvailable will return true is if the application is running on a computer that is connected to a hub or router where the hub or router has lost the upstream connection.
在网络上Ping一个主机名
Ping和PingReply类允许应用程序通过从主机获得回复来确定是否可以通过网络访问远程计算机。这些类可以在System.Net.NetworkInformation命名空间中找到。以ping主机为例。
protected bool CheckConnectivity(string ipAddress)
{
bool connectionExists = false;
try
{
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
if (!string.IsNullOrEmpty(ipAddress))
{
System.Net.NetworkInformation.PingReply reply = pingSender.Send(ipAddress);
connectionExists = reply.Status ==
System.Net.NetworkInformation.IPStatus.Success ? true : false;
}
}
catch (PingException ex)
{
Logger.LogException(ex.Message, ex);
}
return connectionExists;
}
Remarks (As per MSDN): Applications use the Ping class to detect whether a remote computer is reachable. Network topology can determine whether Ping can successfully contact a remote host. The presence and configuration of proxies, network address translation (NAT) equipment, or firewalls can prevent Ping from succeeding. A successful Ping indicates only that the remote host can be reached on the network; the presence of higher level services (such as a Web server) on the remote host is not guaranteed.
欢迎发表意见和建议。编码……快乐!
bool bb = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (bb == true)
MessageBox.Show("Internet connections are available");
else
MessageBox.Show("Internet connections are not available");
我个人觉得Anton和moffeltje的答案最好,但我增加了一个检查,排除VMWare和其他公司设置的虚拟网络。
public static bool IsAvailableNetworkActive()
{
// only recognizes changes related to Internet adapters
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) return false;
// however, this will include all adapters -- filter by opstatus and activity
NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
return (from face in interfaces
where face.OperationalStatus == OperationalStatus.Up
where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
where (!(face.Name.ToLower().Contains("virtual") || face.Description.ToLower().Contains("virtual")))
select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
}
public static bool Isconnected = false;
public static bool CheckForInternetConnection()
{
try
{
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
{
return true;
}
else if (reply.Status == IPStatus.TimedOut)
{
return Isconnected;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
public static void CheckConnection()
{
if (CheckForInternetConnection())
{
Isconnected = true;
}
else
{
Isconnected = false;
}
}
另一种选择是网络列表管理器API,它适用于Vista和Windows 7。MSDN文章在这里。在本文中有一个下载代码示例的链接,允许您这样做:
AppNetworkListUser nlmUser = new AppNetworkListUser();
Console.WriteLine("Is the machine connected to internet? " + nlmUser.NLM.IsConnectedToInternet.ToString());
请确保从COM选项卡中添加对网络列表1.0类型库的引用…它将显示为NETWORKLIST。