title: Fastest way to test internet connection
body: <p>C# 2008 SP1</p>
  
  <p>I am using this code to connect to our client website. This is for a softphone application. Before the user makes a call, the softphone has to test if there is an active Internet connection. </p>
  
  <p>So, want I have done is used the httpWebRequest class to connect to our clients website. If the response is ok, then the Internet connection can proceed. </p>
  
  <p>However, I have noticed that the response is taking too long to respond. I am not sure if this is not a very efficient way to test. </p>
  
  <p>However, when I browse to their website, it takes less than a second to load the page. But takes too long when I use the HttpWebRequest class</p>
  
  <p>So requirements for this are:</p>
  
  <p>Sometime a proxy will be used at the client's office. To I can't use the TCPClient class (doesn't have a proxy property).</p>
  
  <p>The proxy doesn't support SOCKS so cannot use the Sockets class.</p>
  
  <p>I need to use a timeout property. So cannot use the WebClient class. This is because the softphone would freeze until a response is returned. So timeout after a few seconds.</p>
  
  <p>So the only one I can think of is the HttpWebRequest class.</p>
  
  <pre><code>  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.xxxxxxxxx.com");
              request.Timeout = 5000;
              request.Credentials = CredentialCache.DefaultNetworkCredentials;
              HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  
              if (response.StatusCode == HttpStatusCode.OK)
              {
                  Console.WriteLine("IsSIPServerAvailable: " + response.StatusCode);
                  isAvailable = true;
              }
  </code></pre>
  
  <p>======== Edit using p\Invoke ====</p>
  
  <pre><code> [DllImport("wininet.dll", CharSet = CharSet.Auto)]
      private extern static bool InternetGetConnectedState(ref InternetConnectionState_e lpdwFlags, int dwReserved);
  
   [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
      }
  
   // In function for checking internet
   InternetConnectionState_e flags = 0;          
   bool isConnected = InternetGetConnectedState(ref flags, 0);
  </code></pre>