Checking Internet Availability using C#

While developing Internet applications, this is important to check whether the internet connection is available or not. We can achieve this with few lines of code.

Step 1: Include the following Namespace to your class.

using System.Runtime.InteropServices;

This Namespace is necessary to call a function exported from unmanaged DLL.

Step 2:  Use the following lines of code to import a function from the unmanaged DLL.

[DllImport("wininet.dll",CharSet=CharSet.Auto)] 

static extern bool InternetGetConnectedState(ref ConnectionState lpdwFlags, int dwReserved);

Parameters

lpdwFlags - Pointer to a variable that receives the connection description. This parameter can be one or more of the following values:

Value Meaning
INTERNET_CONNECTION_CONFIGURED
0x40
Local system has a valid connection to the Internet, but it might or might not be currently connected.
INTERNET_CONNECTION_LAN
0x02
Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_MODEM
0x01
Local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_MODEM_BUSY
0x08
No longer used.
INTERNET_CONNECTION_OFFLINE
0x20
Local system is in offline mode.
INTERNET_CONNECTION_PROXY
0x04
Local system uses a proxy server to connect to the Internet.
INTERNET_RAS_INSTALLED
0x10
Local system has RAS installed.

dwReserved - Must be zero.

Return Values: Returns TRUE if there is an Internet connection, or FALSE otherwise.

Create a following enumeration for first parameter [lpdwFlags].

[Flags] enum ConnectionState: int
{
INTERNET_CONNECTION_MODEM = 0x1,
INTERNET_CONNECTION_LAN = 0x2,
INTERNET_CONNECTION_PROXY = 0x4,
INTERNET_RAS_INSTALLED = 0x10,
INTERNET_CONNECTION_OFFLINE = 0x20,
INTERNET_CONNECTION_CONFIGURED = 0x40
}

Step 3: Create a instance of ConnectionState enumeration type and set value to 0.

ConnectionState Description = 0;

Step 4: Call the InternetGetConnectedState function in your class.

txtConnectionFlag.Text = InternetGetConnectedState(ref Description, 0).ToString();
txtConnectionState.Text = Description.ToString();

You might also like...

Comments

M M Harinath

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“An expert is a man who has made all the mistakes that can be made in a very narrow field” - Niels Bohr