I have this method:
public static void testConnection()
{
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");
}
}
I suppose it would tell me whether the connection is available or not but it always return true (and print the 1st message) even when I'm sure there is no connection. What I'm doing wrong?
P.S.: I'm still learning C#.
You have a different opinion on the meaning of 'connection' than the manual does. As far as the operating system is concerned, you have a connection when there is a patched ethernet cable connected to your NIC, or when your wireless card is connected to an wireless access point, or any connection is active.
The manual also explains this:
If you want to detect internet connectivity, take a look at the
InternetGetConnectedState()
(orInternetCheckConnection()
, to check for accessibility of a specific host) methods from the WinINet API.I think this method is more appropriate:
Please correct me if I am wrong but as far as I can see the method you are using is checking network connectivity and not necessarily internet connectivity. I would assume if you are on a network of any sort this would return true regardless of the internet being available or not? See this.
I have noticed that one way of checking for internet connectivity is as follows:
The above code can be found (in VB.Net by reading the comment from Joacim Andersson [MVP]) in the following post.
Note: The latest edit was suggested by AceInfinity but was rejected in community review. My reputation is too low to override this so I made the change myself.
From msdn:
One of these examples could be your case:
From MSDN (emphasis is mine):
If with "connection" you mean Internet connection then you should
DllImport
the function InternetCheckConnection orInternetQueryOption
.Instead if what you need is just to know if computer is connected to any useful LAN the best thing you can do is to iterate network connection by yourself and to filter (using NetworkInterfaceType,
IsReceiveOnly
andOperationalStatus
) what you're not interested too.Note that we are using the
Windows.Networking.Connectivity.NetworkInformation
and not theSystem.Net.NetworkInformation
namespace.Basically what ventura8 said. I would comment his solution, mentioning the namespaces, but I lack enough reputation.