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
0×40 - Local system has a valid connection to the Internet, but it might or might not be currently connected.
INTERNET_CONNECTION_LAN
0×02 - Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_MODEM
0×01 - Local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_MODEM_BUSY
0×08 - No longer used.
INTERNET_CONNECTION_OFFLINE
0×20 - Local system is in offline mode.
INTERNET_CONNECTION_PROXY
0×04 - Local system uses a proxy server to connect to the Internet.
INTERNET_RAS_INSTALLED
0×10 - 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 = 0×1,
INTERNET_CONNECTION_LAN = 0×2,
INTERNET_CONNECTION_PROXY = 0×4,
INTERNET_RAS_INSTALLED = 0×10,
INTERNET_CONNECTION_OFFLINE = 0×20,
INTERNET_CONNECTION_CONFIGURED = 0×40
}
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.
string state = InternetGetConnectedState(ref Description, 0).ToString();
string desc = Description.ToString();
txtState.Text = state;
txtDesc.Text = desc;
