C# 使用 .NET 检查 Internet 连接的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2031824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to check for Internet connectivity using .NET?
提问by Mohit Deshpande
What is the fastest and most efficient way to check for Internet connectivity in .NET?
在 .NET 中检查 Internet 连接的最快和最有效的方法是什么?
采纳答案by ChaosPandion
Something like this should work.
像这样的事情应该有效。
public static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (client.OpenRead("http://google.com/generate_204"))
return true;
}
catch
{
return false;
}
}
回答by Leo
There is absolutely no way you can reliablycheck if there is an internet connection or not (I assume you mean access to the internet).
您绝对无法可靠地检查是否有互联网连接(我假设您的意思是访问互联网)。
You can, however, request resources that are virtually never offline, like pinging google.com or something similar. I think this would be efficient.
但是,您可以请求几乎从不离线的资源,例如 ping google.com 或类似内容。我认为这将是有效的。
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);
return (reply.Status == IPStatus.Success);
}
catch (Exception) {
return false;
}
回答by slayerIQ
public static bool HasConnection()
{
try
{
System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com");
return true;
}
catch
{
return false;
}
}
That works
那个有效
回答by dbasnett
Instead of checking, just perform the action (web request, mail, ftp, etc.) and be prepared for the request to fail, which you have to do anyway, even if your check was successful.
而不是检查,只需执行操作(Web 请求、邮件、ftp 等)并为请求失败做好准备,即使您的检查成功,您也必须这样做。
Consider the following:
考虑以下:
1 - check, and it is OK
2 - start to perform action
3 - network goes down
4 - action fails
5 - lot of good your check did
If the network is down your action will fail just as rapidly as a ping, etc.
如果网络出现故障,您的操作将像 ping 等一样迅速失败。
1 - start to perform action
2 - if the net is down(or goes down) the action will fail
回答by Jaime Macias
A test for internet connection by pinging Google:
通过 ping Google 测试互联网连接:
new Ping().Send("www.google.com.mx").Status == IPStatus.Success
回答by gierow
Another option is the Network List Manager API which is available for Vista and Windows 7. MSDN article here. In the article is a link to download code samples which allow you to do this:
另一种选择是网络列表管理器 API,它可用于 Vista 和 Windows 7。此处为 MSDN 文章。文章中提供了一个下载代码示例的链接,您可以使用它来执行此操作:
AppNetworkListUser nlmUser = new AppNetworkListUser();
Console.WriteLine("Is the machine connected to internet? " + nlmUser.NLM.IsConnectedToInternet.ToString());
Be sure to add a reference to Network List 1.0 Type Library from the COM tab... which will show up as NETWORKLIST.
确保从 COM 选项卡添加对 Network List 1.0 Type Library 的引用...,它将显示为 NETWORKLIST。
回答by Hari Prasath
bool bb = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (bb == true)
MessageBox.Show("Internet connections are available");
else
MessageBox.Show("Internet connections are not available");
回答by PJRobot
I disagree with people who are stating: "What's the point in checking for connectivity before performing a task, as immediately after the check the connection may be lost". Surely there is a degree of uncertainty in many programming tasks we as developers undertake, but reducing the uncertainty to a level of acceptance is part of the challenge.
我不同意有人说:“在执行任务之前检查连接有什么意义,因为在检查之后连接可能会立即丢失”。当然,我们作为开发人员承担的许多编程任务都存在一定程度的不确定性,但将不确定性降低到可接受的水平是挑战的一部分。
I recently ran into this problem making an application which including a mapping feature which linked to an on-line tile server. This functionality was to be disabled where a lack of internet connectivity was noted.
我最近在制作一个应用程序时遇到了这个问题,该应用程序包含链接到在线图块服务器的映射功能。在注意到缺乏互联网连接的情况下,将禁用此功能。
Some of the responses on this page were very good, but did however cause a lot of performance issues such as hanging, mainly in the case of the absence of connectivity.
此页面上的一些响应非常好,但确实导致了许多性能问题,例如挂起,主要是在没有连接的情况下。
Here is the solution that I ended up using, with the help of some of these answers and my colleagues:
在其中一些答案和我的同事的帮助下,这是我最终使用的解决方案:
// Insert this where check is required, in my case program start
ThreadPool.QueueUserWorkItem(CheckInternetConnectivity);
}
void CheckInternetConnectivity(object state)
{
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
using (WebClient webClient = new WebClient())
{
webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
webClient.Proxy = null;
webClient.OpenReadCompleted += webClient_OpenReadCompleted;
webClient.OpenReadAsync(new Uri("<url of choice here>"));
}
}
}
volatile bool internetAvailable = false; // boolean used elsewhere in code
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
internetAvailable = true;
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
// UI changes made here
}));
}
}
回答by Anton
Does not solve the problem of network going down between checking and running your code but is fairly reliable
不能解决检查和运行代码之间网络中断的问题,但相当可靠
public static bool IsAvailableNetworkActive()
{
// only recognizes changes related to Internet adapters
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
// 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)
select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
}
return false;
}
回答by Kamran Shahid
NetworkInterface.GetIsNetworkAvailable
is very unreliable. Just have some VMware or other LAN connection and it will return wrong result.
Also about Dns.GetHostEntry
method I were just concerned about whether test URL might be blocked in the environment where my application going to deploy.
NetworkInterface.GetIsNetworkAvailable
非常不可靠。只要有一些 VMware 或其他 LAN 连接,它就会返回错误的结果。另外关于Dns.GetHostEntry
方法,我只关心测试 URL 是否可能在我的应用程序要部署的环境中被阻止。
So another way I found out is using InternetGetConnectedState
method.
My code is
所以我发现的另一种方法是使用InternetGetConnectedState
方法。我的代码是
[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool CheckNet()
{
int desc;
return InternetGetConnectedState(out desc, 0);
}