C#检测是否有网络连接

C#检测是否有网络连接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//使用DllImport需导入命名空间
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;

namespace CheckNetwork
{
    class Program
    {
        static void Main(string[] args)
        {
            bool isConn = IsConnectedInternet();


            bool isConn2= IsConnectedToInternet2();

            Console.ReadKey();
        }

        #region 第二种方法
        public static bool IsConnectedToInternet2()
        {
            string host ="www.baidu.com";  
            bool result = false;
            Ping p = new Ping();
            try
            {
                PingReply reply = p.Send(host, 3000);
                if (reply.Status == IPStatus.Success)
                    return true;
            }
            catch (Exception ex)
            {

            }
            return result;
        }
        #endregion


        //导入判断网络是否连接的 .dll //判断网络状况的方法,返回值true为连接,false为未连接 
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState( ref int Description, int ReservedValue);

        /// <summary>
        /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败
        /// </summary>
        /// <returns></returns>
        public static bool IsConnectInternet()
        {
            int Description = 0;
            return InternetGetConnectedState(ref Description, 0);
        }

        /// <summary>
        /// 判断本地的连接状态
        /// </summary>
        private static bool IsConnectedInternet()
        {
            int dwFlag = new int();
            if (!InternetGetConnectedState( ref dwFlag, 0))
            {
                Console.WriteLine("当前没有联网,请您先联网后再进行操作!");
                if ((dwFlag & 0x14) == 0) return false;
               System.Diagnostics.Debug.WriteLine("本地系统处于脱机模式。");
                return false;
            }
            else
            {
                if ((dwFlag & 0x01) != 0)
                {
                    Console.WriteLine("调制解调器上网。");
                    return true;
                }
                else if ((dwFlag & 0x02) != 0)
                {
                    Console.WriteLine("网卡上网。");
                    return true;
                }
                else if ((dwFlag & 0x04) != 0)
                {
                    Console.WriteLine("代理服务器上网。");
                    return true;
                }
                else if ((dwFlag & 0x40) != 0)
                {
                    Console.WriteLine("虽然可以联网,但可能链接也可能不连接。");
                    return true;
                }
            }

            return false;
        }
    }
}

 

代码示例收集自网络。

 

posted on 2022-07-25 11:10  荆棘人  阅读(1668)  评论(0编辑  收藏  举报

导航