• 0

C# Detect If Internet is available


Question

I'm working on a new project and I'm also entering new waters.

For my app I need a simple internet presence detection notification in my status bar.

How would I do If internet available= Yes, else= no?

Thx

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

You need to put a wrapper function around a WININET API call:

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

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

Source: http://weblogs.asp.net/wim/archive/2004/07/12/180608.aspx

Link to comment
Share on other sites

  • 0
or a less reliable method would be to try and either ping or open a particular website and see if it works.

:)

I'm guessing this is the less reliable method you are talking about...

public Boolean check_Availability()
{
	try
	{
		TcpClient tcp_Client = new TcpClient("www.google.com", 80);
		tcp_Client.Close();

		return true;
	}
	catch (Exception) { return false; }
}

Link to comment
Share on other sites

  • 0
I'm guessing this is the less reliable method you are talking about...

public Boolean check_Availability()
{
	try
	{
		TcpClient tcp_Client = new TcpClient("www.google.com", 80);
		tcp_Client.Close();

		return true;
	}
	catch (Exception) { return false; }
}

Yep :)

Which method did you end up using Kalint?

Link to comment
Share on other sites

  • 0

I prefer to use

		using System.Runtime.InteropServices;

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

		public static bool IsInternetAvailable()
		{
			if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
			{
				int nDescription;
				return InternetGetConnectedState(out nDescription, 0);
			}

			return false;
		}

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.