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
|
Local system has a valid connection to the Internet, but it might or might not be currently connected. |
INTERNET_CONNECTION_LAN
|
Local system uses a local area network to connect to the Internet. |
INTERNET_CONNECTION_MODEM
|
Local system uses a modem to connect to the Internet. |
INTERNET_CONNECTION_MODEM_BUSY
|
No longer used. |
INTERNET_CONNECTION_OFFLINE
|
Local system is in offline mode. |
INTERNET_CONNECTION_PROXY
|
Local system uses a proxy server to connect to the Internet. |
INTERNET_RAS_INSTALLED
|
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