j-nunn.com

How to check if your computer is connected to the internet with C#.

One problem I have been working on is how to check if the host pc has an internet connection available.The answer is surprisingly easy, the solution is to use P/Invoke to call InternetGetConnectedState, which is a Windows API function that returns a Boolean to indicate if the host machine has an active internet connection.

This function takes two arguments :

The first is a pointer to a variable that receives the connection description. This parameter may return a valid flag even when the function returns FALSE. 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.

The second one is a reserved variable that must be set to 0.

 

First Import the external DLL into your application

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(ref InternetConnectionState_e lpdwFlags, int dwReserved);


then add an enumeration to define the connection state (use of a modem, use of a proxy, offline mode..)

[Flags]
enum InternetConnectionState_e : 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
}

 

It is then a fairly easy matter of calling the method to get the current connectivity state of the host.

public Boolean IsConnectedToInternet( )
    {
        Boolean isConnected;
        InternetConnectionState_e flags = 0;         
        isConnected = InternetGetConnectedState(ref flags, 0);
        return isConnected;
    }

Post a comment

  1. Formatting options
       
     
     
     
     
       
Copyright © 2010 John Nunn
This site is powered by