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
|
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();
Related articles
Related discussion
-
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
by virtualking (0 replies)
-
How to optimize mysql subquery performance?
by Jayaram P (0 replies)
-
C# video Editing/rendering
by pkuchaliya (0 replies)
-
How to Fill DataSet with more records (around 1 lakh) in a faster way
by Jayaram P (0 replies)
-
Can't print on the network with MSADESS ??
by anatha1 (2 replies)
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...
This article is a Bomb
!--removed tag-->