添加引用:網絡
using System.Runtime.InteropServices;spa
using System.Net.NetworkInformation;code
[DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(int Description, int ReservedValue); #region 方法一 /// <summary> /// 用於檢查網絡是否能夠鏈接互聯網,true表示鏈接成功,false表示鏈接失敗 /// </summary> /// <returns></returns> public static bool IsConnectInternet() { int Description = 0; return InternetGetConnectedState(Description, 0); } #endregion 方法一 #region 方法二 /// <summary> /// 用於檢查IP地址或域名是否能夠使用TCP/IP協議訪問(使用Ping命令),true表示Ping成功,false表示Ping失敗 /// </summary> /// <param name="strIpOrDName">輸入參數,表示IP地址或域名</param> /// <returns></returns> public static bool PingIpOrDomainName(string strIpOrDName) { try { Ping objPingSender = new Ping(); PingOptions objPinOptions = new PingOptions(); objPinOptions.DontFragment = true; string data = ""; byte[] buffer = Encoding.UTF8.GetBytes(data); int intTimeout = 120; PingReply objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions); string strInfo = objPinReply.Status.ToString(); if (strInfo == "Success") { return true; } else { return false; } } catch (Exception) { return false; } } #endregion 方法二
調用我就不寫了,相信你們都會。orm