What is the fastest and most efficient way to check for Internet connectivity in .NET?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
That works
Pinging google.com introduces a DNS resolution dependency. Pinging 8.8.8.8 is fine but Google is several hops away from me. All I need to do is to ping the nearest thing to me that is on the internet.
I can use Ping's TTL feature to ping hop #1, then hop #2, etc, until I get a reply from something that is on a routable address; if that node is on a routable address then it is on the internet. For most of us, hop #1 will be our local gateway/router, and hop #2 will be the first point on the other side of our fibre connection or whatever.
This code works for me, and responds quicker than some of the other suggestions in this thread because it is pinging whatever is nearest to me on the internet.
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:
Be sure to add a reference to Network List 1.0 Type Library from the COM tab... which will show up as NETWORKLIST.
I am having issue on those method on my 3g Router/modem, because if internet is disconnected the router redirects the page to its response page, so you still get a steam and your code think there is internet. Apples (or others) have a hot-spot-dedection page which always returns a certain response. The following sample returns "Success" response. So you will be exactly sure you could connect the internet and get real response !
I wouldn't think it's impossible, just not straightforward.
I've built something like this, and yes it's not perfect, but the first step is essential: to check if there's any network connectivity. The Windows Api doesn't do a great job, so why not do a better job?
It's pretty simple, but it really helps improve the quality of the check, especially when you want to check various proxy configurations.
So:
Does not solve the problem of network going down between checking and running your code but is fairly reliable