0

I already read some of the questions posted here and I found this post to be the most reliable regarding this matter: What is the best way to check for Internet connectivity using .NET?

But what if the network where the interface is connected have google blocked? (e.g. Internet in China)

Arch
  • 25
  • 8
  • I think you need a server in the free world in that case, which you control and can ensure stays available. Point `WebClient` at that if google cannot be guaranteed to be available. – Tanveer Badar Apr 26 '18 at 03:54

2 Answers2

5

If you're checking for internet connectivity, you probably have a reason... meaning you're looking to use some specific web resource. So check against that resource.

Even better, don't check at all. Internet services can go up or down at any moment... including the moment in between when you run your check and when you try to use the service. That means anything you do has to be able to handle failure anyway. So just don't run the check; put the work into your exception handler instead.

I know that may sound slow, or strange to use exception handling for flow control. But the main reason not to use exceptions for flow control is it's nearly the slowest thing you can do in all of computer science. You know what's even worse? Waiting for network packets to travel half way around the world or timeout, that's what.

In the rare case when you just want to show general internet status to the user, you can do it the same way Microsoft does, and use www.msftncsi.com.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
1

If what you want is to check the state of the internet in .Net without depending on WebClient class or Google, this is the best way

First, import the DLL wininet [System.Runtime.InteropServices.DllImport("wininet.dll")]

Then, call the static extern bool InternetGetConnectedState(...)

This returns true if the internet connects and false if it can not connect, regardless of Google:

[System.Runtime.InteropServices.DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

public static bool IsConnected()
{
     return InternetGetConnectedState(out int description, 0);         
}

Where:

if(IsConnected())
{
   //Internet is connected
}
else
{
   //Internet is not connected
}
Héctor M.
  • 2,302
  • 4
  • 17
  • 35