判断网络类(获取mac) InternetCheck

using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Management;
namespace Share
{
    /// <summary>
    /// 判断网络类
    /// </summary>
    public class InternetCheck
    {
        //单例模式
        private static InternetCheck m_InternetCheck = new InternetCheck();
        public static InternetCheck Instance() { return m_InternetCheck; }

        [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>
        /// ping 具体的网址看能否ping通,true通,false不通
        /// </summary>
        /// <param name="strNetAdd"></param>
        /// <returns></returns>
        public static bool PingNetAddress(string strNetAdd)
        {
            bool Flage = false;
            Ping ping = new Ping();
            try
            {
                PingReply pr = ping.Send(strNetAdd, 3000);
                if (pr.Status == IPStatus.TimedOut)
                {
                    Flage = false;
                }
                if (pr.Status == IPStatus.Success)
                {
                    Flage = true;
                }
                else
                {
                    Flage = false;
                }
            }
            catch
            {
                Flage = false;
            }
            return Flage;
        }
        #endregion

        /// <summary>
        /// 获取Mac
        /// </summary>
        /// <returns></returns>
        public static string GetMAC()
        {
            string mac = "";
            using (ManagementObjectSearcher nisc = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration"))
            {
                foreach (ManagementObject nic in nisc.Get())
                {
                    if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                    {
                        //mac = string.Format("{0} - {1}", nic["ServiceName"], nic["MACAddress"]);
                        mac = string.Format("{0}", nic["MACAddress"]);
                    }
                }
                mac = mac.Replace(":", "-");
            }
            return mac;
        }
        /// <summary>
        /// 获取电脑唯一标识
        /// </summary>
        /// <returns></returns>
        public static string GetComputerIdentification()
        {
            string computName = System.Net.Dns.GetHostName();
            //return "G01701002";
            return computName;
        }


    }
}

 

posted @ 2018-05-10 16:19  三小  阅读(291)  评论(0编辑  收藏  举报