2012-07-06 71 views
1

可能重複:
check whether internet connection is available with C#如何知道MS Windows是否存在紅色或互聯網連接?

我只是想知道,我們必須用它來檢測編程(C#)的方法,如果MS Windows有活着互聯網/紅色連接或不。

可以嗎?

謝謝!

例如:如果我放下WIFI我怎麼能知道有任何連接?

+1

類似:http://stackoverflow.com/questions/2916243/detect-when-network-cable-unplugged – 2012-07-06 19:30:02

+0

我還發現這個答案也很好! http://stackoverflow.com/questions/843810/fastest-way-to-test-internet-connection – 2012-07-06 19:41:55

回答

2

看看在Ping class

 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); 
     } 
+1

ICMP Ping由一些路由器/配置擋着。 – 2012-07-07 03:28:47

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; 
     } 
    } 

的方法嘗試加載谷歌的網址,如果它加載返回true,false,如果它不是。

+0

你認爲Ping方法更快嗎?要麼? – 2012-07-06 19:23:54

+0

不知道原始速度 - 此方法返回適合我的目的的結果。 – 2012-07-06 19:25:37

+0

全部取決於你閱讀的網站有多大是 – 2012-07-06 19:26:36

相關問題