之前写程序中的一段代码,特记录一下。
#region 根据多个地址的ping的情况判断当前是否能够连接互联网 /// <summary> /// 根据多个地址的ping的情况判断当前是否能够连接互联网 /// </summary> /// <param name="urls"></param> /// <returns></returns> public static bool MyPing(string[] urls) { //http://www.cnblogs.com/babycool bool isconn = true; Ping ping = new Ping(); int errorCount = 0; try { PingReply pr; for (int i = 0; i < urls.Length; i++) { pr = ping.Send(urls[i]); if (pr.Status != IPStatus.Success) { errorCount++; } //当前ping的状态 Console.WriteLine("Ping " + urls[i] + " " + pr.Status.ToString()); } } catch (Exception) { errorCount = urls.Length; } //如果错误次数等于urls的个数 说明每个地址访问都失败了 if (errorCount == urls.Length) { isconn = false; } return isconn; } #endregion
#region 判断当前是否联网 /// <summary> /// 判断当前是否联网 /// </summary> /// <returns></returns> public static bool ZXPing() { string[] urls = { "www.baidu.com", "www.qq.com", "www.sina.com.cn" }; return MyPing(urls); } #endregion