views:

436

answers:

1

i have used the following code to check for internet connection it works perfectly without firewall & proxy. how do i check net connection in firewall & proxy mode. please help me

private static ManualResetEvent connectDone = new ManualResetEvent(false);
public static bool IsInternetConnected()
{
 int Desc;
 string[] sitesList = { "www.google.co.in", "www.microsoft.com", "www.sun.com" };
 bool status;
 status = InternetGetConnectedState(out Desc, 0);
 if (status)
 {
  try
  {
  connectDone.Reset();
  TcpClient client = new TcpClient();

  client.BeginConnect(sitesList[0], 80, new AsyncCallback(ConnectCallback), client);
  connectDone.WaitOne(1000, false);
  if (client.Connected)
  status = true;
  else
  status = false;
  client.Close();
  }
  catch (System.Exception ex)
  {
  BringDebug.WriteToLog("BringNet", "IsInternetConnected", ex.Message);
  return false;
  }
 }
 else
 {
  return false;
 }

 return status;
}

private static void ConnectCallback(IAsyncResult ar)
{
 try
 {
  TcpClient client1 = (TcpClient)ar.AsyncState;
  client1.EndConnect(ar); // Complete the connection.
  connectDone.Set(); // trigger the connectDone event 
 }
 catch (Exception e)
 {
  Console.WriteLine(e.ToString());
 }
}
+3  A: 

If you use WebRequest instead of TcpClient, it should use the system default proxy etc. It'll also be less code :)

For example:

using System;
using System.Net;

class Test
{
    static void Main()
    {
        var request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
        request.Timeout = 1000;

        try
        {
            using (var response = request.GetResponse()) {}
            Console.WriteLine("Success");
        }
        catch (WebException)
        {
            Console.WriteLine("No connection");
        }
    }
}
Jon Skeet
thanks for your response, but i think it is slower method than previous one , is there any idea to speed up
JKS
When you say you *think* it is slower - have you measured it? Admittedly it will actually fetch a response rather than just connecting, but I'd expect it to be *adequately* fast.
Jon Skeet
(One option for speeding it up by the way, at the cost of some complexity: make the three requests in parallel.)
Jon Skeet
i get "The operation has timed out" message every first time i ran the code
JKS
So increase the timeout.
Jon Skeet
i get the same error again eventhough, i set the timeout to 2500
JKS
That suggests it really is timing out. Try using Wireshark to see what's going on.
Jon Skeet
Ok thank you for your quick response, i will check
JKS