2

我已使用以下代码检查互联网连接,它可以在没有防火墙和代理的情况下完美运行。如何在防火墙和代理模式下检查网络连接。请帮我

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());
    }
}
4

1 回答 1

5

如果你使用WebRequest而不是TcpClient,它应该使用系统默认代理等。它的代码也会更少:)

例如:

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");
        }
    }
}
于 2009-09-10T06:35:59.590 回答