How to 100% check internet availability

Ok I am posting this because it took me several days to figure out a way to check the internet properly.
Pinging - could be disabled by the network i.e. unreliable

public static bool HasConnection()
{
	try
	{
		using (var client = new WebClient())
		using (var stream = new WebClient().OpenRead("http://www.google.com"))
		{
			return true;
		}
	}
	catch
	{
		return false;
	}
}

bool CheckConnection(string URL)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Timeout = 5000;
        request.Credentials = CredentialCache.DefaultNetworkCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK) return true;
        else return false;
    }
    catch
    {
		return false;
    }
}

both of these methods returned true if connected and false if not connected but what if you were connected to a network but needed to log-in to view content still (getting routed to a log-in page when trying to browse)
If that is the case then these methods will still return true since they got a response but it really didn’t get the right one.

I might be over-simplifying the issue, but this works for me:

IEnumerator checkInternetConnection(Action<bool> action){
	WWW www = new WWW("http://google.com");
	yield return www;
	if (www.error != null) {
		action (false);
	} else {
		action (true);
	}
} 

void Start(){
    StartCoroutine(checkInternetConnection((isConnected)=>{
        // handle connection status here
    }));
}

Using this method you can see if you are able to view the page you wanted or not by accessing the html of that page you can read it to see if you got redirected or not.
this example uses www.google.com as it’s check

using System.Net;
public string GetHtmlFromUri(string resource)
{
	string html = string.Empty;
	HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resource);
	try
	{
		using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
		{
			bool isSuccess = (int)resp.StatusCode < 299 && (int)resp.StatusCode >= 200;
			if (isSuccess)
			{
				using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
				{
					//We are limiting the array to 80 so we don't have
					//to parse the entire html document feel free to 
					//adjust (probably stay under 300)
					char[] cs = new char[80];
					reader.Read(cs, 0, cs.Length);
					foreach(char ch in cs)
					{
						html +=ch;
					}
				}
			}
		}
	}
	catch
	{
		return "";
	}
	return html;
}

This is to call the function

using System.Net;
void Start()
{
	string HtmlText = GetHtmlFromUri("http://google.com");
	if(HtmlText == "")
	{
		//No connection
	}
	else if(!HtmlText.Contains("schema.org/WebPage"))
	{
		//Redirecting since the beginning of googles html contains that 
		//phrase and it was not found
	}
	else
	{
		//success
	}
}

Great Code. Although I came across a major problem with this script. This script correctly shows result what it is intended for. I tried to make it check for connection avilability:

public static bool IsConnected(string hostedURL="http://www.google.com")
{
	try{
		string HtmlText = GetHtmlFromUri(hostedURL);
		if(HtmlText == "" )
			return false;
		else
			return true;
        }
	catch(IOException ex)
	{
		return false;
	}
} 

It is working fine but, when the machine is offline, It freezes the application(Unity Editor) and after 10 seconds or so it resumes. Is there anyway I can implement a timeout feature so as to specifiy for how long will it check?

This asset is an easy solution, with support to use major company network accessibility detection urls in addition to having the option to using your own:
Internet Reachability Verifier
https://strobotnik.com/unity/internetreachabilityverifier/

Application.internetReachability work fine for me.

 if (Application.internetReachability != NetworkReachability.NotReachable)
{
//Connection OK
}
else
{
//NoInternetConnection
}

it works exactly what you want

if (Application.internetReachability == NetworkReachability.NotReachable) {

		Debug.log("No Internet Connection");

	} else {
	Debug.log("Connected");
	}

If your app gets popular, Google will id your requests as a DOS attack and stop responding to them. Been there, done that. Send these types of requests to a simple page on your own servers.

Heres my way if it helps, it works fine for me.

var url : String = "I used a google docs page with one character here";

function Start(){
   var www : WWW = new WWW(url);
   yield www;
   if(www.isDone && www.bytesDownloaded > 0){
   print("done");
   }
if(www.isDone && www.bytesDownloaded == 0){
   print("no connection");

   }

}

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable ();

///


/// Checks the internet connection.
///

/// true, if internet connection was checked, false otherwise.
public static bool CheckInternetConnection()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://www.example.com”);
request.Timeout = 5000;
request.Method = “HEAD”;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

			if (response.StatusCode == HttpStatusCode.OK)	return true;
			else return false;
		}
		catch
		{
			return false;
		}
	}

Sorry for digging up this question but since it’s the first hit on google I thought it might be good to share with the future stumble ups that Unity apparently implemented this in engine: Unity - Scripting API: Network.TestConnection

EDIT:

Or maybe they didn’t! It Network.TestConnection(); always returns ConnectionTesterStatus.Undetermined to me for some raason

This seems to work for me:

public static bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
            using (client.OpenRead("https://xxxxxx.com/"))    // "http://google.com/generate_204"))
                return true;
        }
        catch
        {
            return false;
        }
    }