1. 調用 cmd 中的 ping 命令,分析輸出信息來確定網絡是否連接
1 //導入命名空間 2 using System.Net.NetworkInformation; 3 4 5 /// <summary> 6 /// Ping命令檢測網絡是否暢通 7 /// </summary> 8 /// <param name="url">URL地址</param> 9 /// <returns>是否ping通</returns> 10 public static bool ChinarPing(string url) 11 { 12 Ping ping = new Ping(); 13 try 14 { 15 PingReply pr = ping.Send(url); 16 if (pr.Status == IPStatus.Success) 17 { 18 return true; 19 } 20 else 21 { 22 return false; 23 } 24 } 25 26 catch 27 { 28 isSucceed = false; 29 } 30 }
2. 使用InternetGetConnectedState () 函數
public const int INTERNET_CONNECTION_MODEM = 0x01; //調制解調器連接到 Internet public const int INTERNET_CONNECTION_LAN = 0x02; //局域網網卡連接到 Internet public const int INTERNET_CONNECTION_PROXY = 0x04; //代理服務器連接到 Internet private const int INTERNET_RAS_INSTALLED = 0x08; //已安裝 RAS public const int INTERNET_CONNECTION_OFFLINE = 0x14; //脫機模式 public const int INTERNET_CONNECTION_CONFIGURED = 0x40; //具有到 Internet 的有效連接,但它當前可能連接也可能不連接
//使用DllImport需導入命名空間 using System.Runtime.InteropServices; //導入判斷網絡是否連接的 .dll //判斷網絡狀況的方法,返回值true為連接,false為未連接 [DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(int Description, int ReservedValue); /// <summary> /// 用於檢查網絡是否可以連接互聯網,true表示連接成功,false表示連接失敗 /// </summary> /// <returns></returns> public static bool IsConnectInternet() { int Description = 0; return InternetGetConnectedState(Description, 0); } /// <summary> /// 判斷本地的連接狀態 /// </summary> private static bool IsConnectedInternet() { int dwFlag = new int(); if (!InternetGetConnectedState(ref dwFlag, 0)) { PrintR("當前沒有聯網,請您先聯網后再進行操作!"); if ((dwFlag & 0x14) == 0) return false; Debug.LogWarning("本地系統處於脫機模式。"); return false; } else { if ((dwFlag & 0x01) != 0) { Print("調制解調器上網。"); return true; } else if ((dwFlag & 0x02) != 0) { Print("網卡上網。"); return true; } else if ((dwFlag & 0x04) != 0) { Print("代理服務器上網。"); return true; } else if ((dwFlag & 0x40) != 0) { Print("雖然可以聯網,但可能鏈接也可能不連接。"); return true; } } return false; }