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 资料的方法
A test for internet connection by pinging Google:
I have seen all the options listed above and the only viable option to check wither the internet is available or not is the "Ping" option. Importing
[DllImport("Wininet.dll")]
andSystem.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
Or any other variation of theNetworkInterface
class does not work well in detecting the availability of the network.These Methods only check if the network cable is plugged in or not.The "Ping option"
if
(Connection is available) returnstrue
if
(Connection is not available and the network cable is plugged in) returnsfalse
if
(Network cable is not plugged in)Throws an exception
The NetworkInterface
if
(Internet Is available)ReturnsTrue
if
(Internet is not Available and Network Cable is Plugged in ) ReturnsTrue
if
(Network Cable is Not Plugged in )returnsfalse
The [DllImport("Wininet.dll")]
if
(Internet Is available)ReturnsTrue
if
(Internet is not Available and Network Cable is Plugged in ) ReturnsTrue
if
(Network Cable is Not Plugged in )returnsfalse
So in case of
[DllImport("Wininet.dll")]
andNetworkInterface
There is no way of knowing if internet connection is available.If you want to notify the user/take action whenever a network/connection change occur.
Use NLM API:
https://msdn.microsoft.com/en-us/library/ee264321.aspx
http://www.codeproject.com/Articles/34650/How-to-use-the-Windows-NLM-API-to-get-notified-of
I have three tests for an Internet connection.
System.Net
andSystem.Net.Sockets
Test 1
Test 2
Test 3
Performing the tests
If you make a
Dictionary
ofString
andBoolean
calledCheckList
, you can add the results of each test toCheckList
.Now, recurse through each
KeyValuePair
using afor...each
loop.If
CheckList
contains aValue
oftrue
, then you know there is an Internet connection.Something like this should work.
System.Net.WebClient