方法一
代碼如下 |
複製代碼 |
public bool CheckForInternetConnection() { bool result = false; try { Ping ping = new Ping(); PingReply replay = ping.Send("114.114.114.114", 2000); if (replay.Status == IPStatus.Success) { result = true; } } catch { } return result; } |
方法二
代碼如下 |
複製代碼 |
public bool CheckForInternetConnection() { bool result = false; try { using (WebClient client = new WebClient()) { client.DownloadString("http://www.111cn.net/"); result = true; } } catch { } return result; } |
方法三
代碼如下 |
複製代碼 |
c#內建的Ping,using System.Net.NetworkInformation; Ping ping = new Ping(); for (int i = iFrom; i <= iTo; i++) { mre1.WaitOne(); string ip = strIP + i.ToString(); label10.Text = "正在掃描主機:" + ip.ToString() ; try { PingReply reply = ping.Send(ip, 100); if (reply.Status == IPStatus.Success) { rtbInfo.AppendText("Host: " + ip.ToString() + "\r"); rtbInfo.ScrollToCaret(); } } catch { rtbInfo.AppendText("發生了一個異常!\r"); } } rtbInfo.AppendText("掃描完畢!\r"); |
說明:NetworkInterface.GetIsNetworkAvailable()僅用於檢測是否有可用的網路連接(網卡),不能用於檢測電腦是否連網。例如撥接的電腦,沒有撥號時也是返回True。