C# 判断连接网络是否正常

来源:互联网 发布:手机上淘宝联盟怎么做 编辑:程序博客网 时间:2024/05/17 03:12

     public static string Main()
        {

            string url = "www.baidu.com;www.sina.com;www.cnblogs.com;www.google.com;www.csdn.com";

            string[] urls = url.Split(new char[] { ';' });

            string cc = CheckServeStatus(urls);
            return cc;
            //Console.ReadKey();

        }
        /// <summary>

        /// 检测网络连接状态

        /// </summary>

        /// <param name="urls"></param>

        public static string CheckServeStatus(string[] urls)
        {

            int errCount = 0;//ping时连接失败个数
            if (!LocalConnectionStatus())
            {

                //Console.WriteLine("网络异常~无连接");
                string s = "网络异常~无连接";
                return s;
            }

            else if (!MyPing(urls, out errCount))
            {

                if ((double)errCount / urls.Length >= 0.3)
                {

                    //Console.WriteLine("网络异常~连接多次无响应");
                    string s = "网络异常~连接多次无响应";
                    return s;
                }

                else
                {

                    // Console.WriteLine("网络不稳定");
                    string s = "网络不稳定";
                    return s;
                }

            }
            else
            {
                //Console.WriteLine("网络正常");
                string s = "网络正常";
                return s;
            }

        }
        #region 网络检测
        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>

        private static bool LocalConnectionStatus()
        {
            System.Int32 dwFlag = new Int32();
            if (!InternetGetConnectedState(ref dwFlag, 0))
            {
                Console.WriteLine("LocalConnectionStatus--未连网!");
                return false;
            }
            else
            {
                if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
                {
                    Console.WriteLine("LocalConnectionStatus--采用调制解调器上网。");
                    return true;
                }
                else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
                {
                    Console.WriteLine("LocalConnectionStatus--采用网卡上网。");
                    return true;
                }
            }
            return false;
        }

 

        /// <summary>

        /// Ping命令检测网络是否畅通

        /// </summary>

        /// <param name="urls">URL数据</param>

        /// <param name="errorCount">ping时连接失败个数</param>

        /// <returns></returns>

        public static bool MyPing(string[] urls, out int errorCount)
        {
            bool isconn = true;
            Ping ping = new Ping();
            errorCount = 0;
            try
            {
                PingReply pr;
                for (int i = 0; i < urls.Length; i++)
                {
                    pr = ping.Send(urls[i]);
                    if (pr.Status != IPStatus.Success)
                    {
                        isconn = false;
                        errorCount++;
                    }
                    Console.WriteLine("Ping " + urls[i] + "    " + pr.Status.ToString());
                }
            }
            catch
            {
                isconn = false;
                errorCount = urls.Length;
            }
            //if (errorCount > 0 && errorCount < 3)
            //  isconn = true;
            return isconn;
        }
        #endregion
        //private static void AppThreadException(object source, System.Threading.ThreadExceptionEventArgs e)
        //{
        //    string errorMsg = string.Format("未处理异常: \n{0}\n", e.Exception.Message);
        //    errorMsg += Environment.NewLine;

        //    // DialogResult result = MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);

        //    //如果点击“中止”则退出程序
        //    // if (result == DialogResult.Abort)
        //    // {
        //    //      Application.Exit();
        //    //  }
        //}

原创粉丝点击