1 /// <summary> 2 /// ping 域名地址是否通畅 3 /// </summary> 4 /// <returns></returns> 5 public async static Task<bool> PingAsync(string ip, int timeout = 5000) 6 { 7 try 8 { 9 var pr = await (new Ping()).SendPingAsync(ip, timeout); 10 if (pr != null && pr.Status == IPStatus.Success)//如果ping成功 11 { 12 return true; 13 } 14 } 15 catch (PingException ex) 16 { 17 Util.SystemStatus.Instance.Network = NetworkStatus.Faulty; 18 Util.Log.Logger.Error("网络连接异常:" + ex.Message); 19 } 20 return false; 21 }
判断是否可以连接
1 /// <summary> 2 /// 判断网络的连接状态 3 /// </summary> 4 /// <returns> 5 /// 网络状态(1-->未联网;2-->采用调治解调器上网;3-->采用网卡上网) 6 ///</returns> 7 public static int GetNetConStatus(string strNetAddress) 8 { 9 int iNetStatus = 0; 10 int dwFlag = new int(); 11 if (!InternetGetConnectedState(ref dwFlag, 0)) 12 { 13 //没有能连上互联网 14 iNetStatus = 1; 15 } 16 else if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0) 17 { 18 //采用调治解调器上网,需要进一步判断能否登录具体网站 19 if (PingNetAddress(strNetAddress)) 20 { 21 //可以ping通给定的网址,网络OK 22 iNetStatus = 2; 23 } 24 else 25 { 26 //不可以ping通给定的网址,网络不OK 27 iNetStatus = 4; 28 } 29 } 30 else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0) 31 { 32 //采用网卡上网,需要进一步判断能否登录具体网站 33 if (PingNetAddress(strNetAddress)) 34 { 35 //可以ping通给定的网址,网络OK 36 iNetStatus = 3; 37 } 38 else 39 { 40 //不可以ping通给定的网址,网络不OK 41 iNetStatus = 5; 42 } 43 } 44 Console.WriteLine("网络状态:" + iNetStatus); 45 return iNetStatus; 46 } 47 48 /// <summary> 49 /// ping 具体的网址看能否ping通 50 /// </summary> 51 /// <param name="strNetAdd"></param> 52 /// <returns></returns> 53 public static bool PingNetAddress(string strNetAdd) 54 { 55 bool Flage = false; 56 Ping ping = new Ping(); 57 try 58 { 59 PingReply pr = ping.Send(strNetAdd, 5000); 60 if (pr.Status == IPStatus.TimedOut) 61 { 62 Flage = false; 63 } 64 if (pr.Status == IPStatus.Success) 65 { 66 Flage = true; 67 } 68 else 69 { 70 Flage = false; 71 } 72 } 73 catch (Exception ex) 74 { 75 Console.WriteLine(ex); 76 Flage = false; 77 } 78 Console.WriteLine("Ping网络状态:" + Flage); 79 return Flage; 80 }