C#實戰小技巧(十七):檢測網絡連接狀況(代碼示例)

	/// <summary>
    /// 網絡檢測
    /// </summary>
    public class NetHelper
    {
        private static ILog LOG = LogManager.GetLogger(typeof(NetHelper));

        private const int INTERNET_CONNECTION_MODEM = 1;
        private const int INTERNET_CONNECTION_LAN = 2;

        [System.Runtime.InteropServices.DllImport("winInet.dll")]
        private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);

        /// <summary>
        /// 判斷本地的連接狀態
        /// </summary>
        /// <returns></returns>
        public static bool LocalConnectionStatus()
        {
            System.Int32 dwFlag = new Int32();
            if (!InternetGetConnectedState(ref dwFlag, 0))
            {
                LOG.Warn("本地未連網");
                return false;
            }
            else
            {
                if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
                {
                    //LOG.Info("採用調制解調器上網");
                    return true;
                }
                else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
                {
                    //LOG.Info("採用網卡上網");
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 檢測網絡是否連接正常
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="timeout">超時時間</param>
        /// <returns></returns>
        public static bool MyPing(string ip, string port, int timeout)
        {
            if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(port))
            {
                LOG.Warn("連接失敗,IP或端口爲空");
                return false;
            }

            bool isConnect = false;
            try
            {
                using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
                {
                    var result = client.BeginConnect(ip, Convert.ToInt32(port), null, null);
                    isConnect = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout));
                    if (!isConnect)
                    {
                        LOG.Warn(new StringBuilder("連接失敗,地址:").Append(ip).Append(":").Append(port).ToString());
                    }

                    client.EndConnect(result);
                    client.Close();
                }
            }
            catch (Exception ex)
            {
                LOG.Error(new StringBuilder("檢測網絡連接出錯:").Append(ex.Message).ToString());
            }

            return isConnect;
        }

        /// <summary>
        /// 檢測網絡連接狀態
        /// </summary>
        /// <param name="urls"></param>
        public static bool CheckServerStatus(string ip, string port)
        {
            if (!LocalConnectionStatus())
            {
                return false;
            }

            if (!MyPing(ip, port, 3000))
            {
                return false;
            }
            else
            {
                //LOG.Info(new StringBuilder(urls).Append("網絡正常"));
                return true;
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章