C# Tips

C# Tip Article

How to check internet connectivity in C#

Since .NET 2.0, there is a method called NetworkInterface.GetIsNetworkAvailable() which returns true if network connection is available. But it does not guarantee that you are connecting to internet since network connectivity might be limited to local network only. In order to check if the machine is actually connected to internet, we can issue http get command to some popular websites such as microsoft.com or google.com.

The following example is using NCSI (Network Connectivity Status Indicator), which is a internet connectivity checking method in Windows OS(Vista or later). Firstly, it checks to see if we can reach Microsoft NCSI test url. Secondly, it check NCSI DNS IP address to make sure we have correct DNS.

bool IsInternetConnected()
{
	const string NCSI_TEST_URL = "http://www.msftncsi.com/ncsi.txt";
	const string NCSI_TEST_RESULT = "Microsoft NCSI";
	const string NCSI_DNS = "dns.msftncsi.com";
	const string NCSI_DNS_IP_ADDRESS = "131.107.255.255";

	try
	{
		// Check NCSI test link
		var webClient = new WebClient();
		string result = webClient.DownloadString(NCSI_TEST_URL);
		if (result != NCSI_TEST_RESULT)
		{
			return false;
		}

		// Check NCSI DNS IP
		var dnsHost = Dns.GetHostEntry(NCSI_DNS);
		if (dnsHost.AddressList.Count() < 0 || dnsHost.AddressList[0].ToString() != NCSI_DNS_IP_ADDRESS)
		{
			return false;
		}
	}
	catch (Exception ex)
	{
		Debug.WriteLine(ex);
		return false;
	}

	return true;
}