1

可能重复:
检查 Internet 连接是否可用 C#

我只想知道我们必须使用哪些方法来以编程方式(C#)检测 MS Windows 是否有活动的 Internet/red 连接或没有。

有可能吗?

谢谢!

例如:如果我放下WIFI,我怎么知道有连接?

4

2 回答 2

2

看看Ping类

       Ping pingSender = new Ping ();
        PingOptions options = new PingOptions ();

        // Use the default Ttl value which is 128,
        // but change the fragmentation behavior.
        options.DontFragment = true;

        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes (data);
        int timeout = 120;
        PingReply reply = pingSender.Send ("www.google.com", timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine ("Address: {0}", reply.Address.ToString ());
            Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
        }
于 2012-07-06T19:18:57.327 回答
0

我使用以下方法检查连接:

public bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead("http://www.google.com"))
            {
                Console.WriteLine("You Have connectity!");
                return true;
            }
        }
        catch
        {
            Console.WriteLine("No internet connection found.");
            return false;
        }
    }

该方法尝试加载 Google 的 URL,如果加载则返回 true,否则返回 false。

于 2012-07-06T19:22:14.510 回答