实时检测网络状态及是否可以连接Internet

发布时间:2017-1-21 21:13:47 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"实时检测网络状态及是否可以连接Internet ",主要涉及到实时检测网络状态及是否可以连接Internet 方面的内容,对于实时检测网络状态及是否可以连接Internet 感兴趣的同学可以参考一下。

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
namespace NetWork
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
            NetworkChange.NetworkAddressChanged+=new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }
        public void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface n in adapters)
            {
                if(n.NetworkInterfaceType!= NetworkInterfaceType.Loopback)
                    Console.WriteLine("Changed   {0} is {1}", n.Name, n.OperationalStatus);
            }
            Console.WriteLine("NetState  :  " + NetState());
        }
        public void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {            
            Console.WriteLine("IsAvailable  :  "+e.IsAvailable);
            Console.WriteLine("NetState  :  " + NetState());
            
        }

        [DllImport("wininet.dll")]
        public static extern bool InternetGetConnectedState(out long lpdwFlags, long dwReserved);

        public static bool NetState()
        {
            //string url = http://www.baidu.com/;
            //if (url.StartsWith("http://")) url = url.Remove(0, "http://".length/);
            //try
            //{
            //    System.Net.IPHostEntry ipHost = System.Net.Dns.GetHostEntry(url);// System.Net.Dns.Resolve(url);
            //    return true;
            //}
            //catch //(System.Net.Sockets.SocketException se)
            //{
            //    //System.Diagnostics.Trace.Write(se.Message);
            //    return false;
            //}
            try
            {
                long lfag;
                if (InternetGetConnectedState(out lfag, 0))
                {                   
                    return true;   
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

      }
}


上一篇:[译] 在Web API 2 中实现带JSON的Patch请求
下一篇:高清(200万像素)多灯红外防水枪型网络摄像机 DH-IPC-HFW5200-IRA

相关文章

相关评论