Library code snippets

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();

Comments

  1. 29 Jul 2009 at 15:56

    This article is a Bomb

Leave a comment

Sign in or Join us (it's free).

M M Harinath

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Want to stay in touch with what's going on? Follow us on twitter!