How to check netconnection in firewall and proxy environment in C #

I used the following code to test internet connection, it works fine without firewall and proxy. how to check network connection in firewall and 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());
    }
}

      

+2


source to share


1 answer


If you use WebRequest

instead TcpClient

, it should use the default proxy, etc. There will 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");
        }
    }
}

      

+5


source







All Articles