C#的网络适配器操作

发布时间:2020-06-16 08:08:02 作者:彭泽0902
来源:网络 阅读:520

   网络的相关设置在项目开发中有较多的应用,有时候需要在项目中对网络信息进行相关设置。主要包含IP设置,网关设置,DHCP设置,DNS设置等相关网络的设置。

    现在提供提供几种相关的辅助方法类。

        /// <summary>
        /// 网络适配器标识符,如:{274F9DD5-3650-4D59-B61E-710B6AF5AB36}
        /// </summary>
        public string NetworkInterfaceId { get; set; }

        /// <summary>
        /// IP地址
        /// </summary>
        public string IpAddress
        {
            get
            {
                string ipAddress;
                var address = GetAddress();
                if (address == null)
                {
                    ipAddress = string.Empty;
                }
                else
                {
                    ipAddress = address.Address.ToString();
                }
                return ipAddress;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// 网关地址
        /// </summary>
        public string Getway
        {
            get
            {              
                string getway;
                if (Getwaryes != null && Getwaryes.Count > 0)
                {

                    getway = Getwaryes[0].Address.ToString() == "0.0.0.0" ? "" : Getwaryes[0].Address.ToString(); 
                }
                else
                {
                    getway =string.Empty;
                }
                return getway;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// DHCP服务器地址
        /// </summary>
        public string DhcpServer
        {
            get
            {
                string dhcpServer;
                if (DhcpServerAddresses != null && DhcpServerAddresses.Count > 0)
                {
                    dhcpServer = DhcpServerAddresses[0].ToString();
                }
                else
                {
                    dhcpServer = string.Empty;
                }
                return dhcpServer;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// MAC地址
        /// </summary>
        public string MacAddres
        {
            get
            {
                string macAddress;
                if (MacAddress == null)
                    macAddress = string.Empty;
                else if (MacAddress.ToString().Length == 12)
                {
                    macAddress = MacAddress.ToString().Insert(4, "-").Insert(9, "-");
                }
                else
                {
                    macAddress = MacAddress.ToString();
                }
                return macAddress;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// 主DNS地址
        /// </summary>
        public string DnsMain
        {
            get
            {
                var dnsMain =string.Empty;

                if (DnsAddresses.Count > 0)
                {
                    if (IsIPAddress(DnsAddresses[0].ToString()))
                    {
                        dnsMain = DnsAddresses[0].ToString();
                    }
                }
                else
                {
                    dnsMain =string.Empty;
                }
                return dnsMain;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// 备用DNS地址
        /// </summary>
        public string DnsBackup
        {
            get
            {
                var dnsBackup = string.Empty;
                if (DnsAddresses.Count > 1)
                {
                    if (IsIPAddress(DnsAddresses[1].ToString()))
                    {
                        dnsBackup = DnsAddresses[1].ToString();
                    }

                }
                else
                {
                    dnsBackup = string.Empty;
                }
                return dnsBackup;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// 子网掩码
        /// </summary>
        public string Mask
        {
            get
            {
                string mask;
                var address = GetAddress();
                if (address == null)
                {
                    mask = "";
                }
                else
                {
                    if (address.IPv4Mask != null) 
                    {
                        mask = address.IPv4Mask.ToString();
                    }
                    else
                    {
                        mask = "255.255.255.0";
                    }
                   
                }
                return mask;
            }
            set { if (value == null) throw new ArgumentNullException(nameof(value)); }
        }

        /// <summary>
        /// DNS集合
        /// </summary>
        public IPAddressCollection DnsAddresses { get; set; }
        /// <summary>
        /// 网关地址集合
        /// </summary>
        public GatewayIPAddressInformationCollection Getwaryes { get; set; }

        /// <summary>
        /// IP地址集合
        /// </summary>
        public UnicastIPAddressInformationCollection IpAddresses { get; set; }

        /// <summary>
        /// DHCP地址集合
        /// </summary>
        public IPAddressCollection DhcpServerAddresses { get; set; }

        /// <summary>
        /// 网卡MAC地址
        /// </summary>
        public PhysicalAddress MacAddress { get; set; }

        /// <summary>
        /// 是否启用DHCP服务
        /// </summary>
        public bool IsDhcpEnabled { get; set; }

        /// <summary>
        /// 描述信息
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// 网络接口类型
        /// </summary>
        /// <returns></returns>
        public string NetworkInterfaceType { get; set; }

        /// <summary>
        /// 速度
        /// </summary>
        public string Speed { get; set; } 

        /// <summary>
        /// 是否是IP地址
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public bool IsIPAddress(string ipAddress)
        {
            const string regexStr = @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$";
            var regex = System.Text.RegularExpressions.Regex.Match(ipAddress, regexStr);
            return regex.Success;
        }

        /// <summary>
        /// 启用DHCP服务
        /// </summary>
        public bool EnableDhcp()
        {
            var wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var moc = wmi.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                if (!(bool)mo["IPEnabled"])
                    continue;
                if (mo["SettingID"].ToString() != NetworkInterfaceId) continue;
                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                mo.InvokeMethod("EnableDHCP", null);
            }
            //查询现适配器接口信息
            var networkAdapter = new NetworkAdapterUtil().GetNeworkAdapterByNetworkInterfaceId(NetworkInterfaceId); 
            return networkAdapter != null && networkAdapter.IsDhcpEnabled;
        }

        /// <summary>
        /// 设置IP地址,子网掩码,网关,DNS,
        /// </summary>
        public bool SetIpAddressSubMaskDnsGetway(string ipAddress, string subMask, string getWay, string dnsMain, string dnsBackup)
        {
            string[] dnsArray;
            if (string.IsNullOrEmpty(dnsBackup))
            {
                dnsArray = new[] { dnsMain };
            }
            else
            {
                dnsArray = new[] { dnsMain, dnsBackup };
            }
            return SetIpAddress(new[] { ipAddress }, new[] { subMask }, new[] { getWay }, dnsArray);

        }

        /// <summary>
        /// 设置IP地址和子网掩码
        /// </summary>
        public bool SetIpAddressAndSubMask(string ipAddress, string subMask)
        {
           return SetIpAddress(new[] { ipAddress }, new[] { subMask }, null, null);

        }


        /// <summary>
        /// 设置IP网关
        /// </summary>
        public bool SetGetWayAddress(string getWay)
        {
            return SetIpAddress(null, null, new[] { getWay }, null);

        }

        /// <summary>
        /// 设置主,备份DNS地址
        /// </summary>
        public bool SetDnsAddress(string dnsMain, string dnsBackup)
        {
            string[] dnsArray;
            if (string.IsNullOrEmpty(dnsBackup))
            {
                dnsArray = new[] { dnsMain };
            }
            else
            {
                dnsArray = new[] { dnsMain, dnsBackup };
            }
            return  SetIpAddress(null, null, null, dnsArray);

        }
        

        /// <summary>
        /// 得到IPV4地址
        /// </summary>
        /// <returns></returns>
        private UnicastIPAddressInformation GetAddress()
        {
            if (IpAddresses == null || IpAddresses.Count <= 0) return null;
            switch (IpAddresses.Count)
            {
                case 3:
                    return IpAddresses[2];
                case 2:
                    return IpAddresses[1];
            }
            return IpAddresses[0];
        }


        /// <summary>
        /// 检查设置IP地址,如果返回空,表示检查通过,为了方便返回就字符串了,没用枚举了
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="subMask"></param>
        /// <param name="getWay"></param>
        /// <param name="dnsMain"></param>
        /// <param name="dnsBackup"></param>
        /// <returns></returns>
        public string IsIPAddress(string ipAddress, string subMask, string getWay, string dnsMain, string dnsBackup)
        {
            if (!string.IsNullOrEmpty(ipAddress))
            {
                if (!IsIPAddress(ipAddress)) return "IP地址格式不对";
            }
           if (!string.IsNullOrEmpty(subMask))
            {
                if (!IsIPAddress(subMask)) return "子网掩码格式不对";
            }
           if (!string.IsNullOrEmpty(getWay))
            {
                if (!IsIPAddress(getWay)) return "网关地址格式不对";
            }
            if (!string.IsNullOrEmpty(dnsMain))
            {
                if (!IsIPAddress(dnsMain)) return "主DNS地址格式不对";
            }
            if (string.IsNullOrEmpty(dnsBackup)) return "";
            return !IsIPAddress(dnsBackup) ? "备用DNS地址格式不对" : "";
        }



        /// <summary>
        /// 设置IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        /// <param name="dns"></param>
        private bool SetIpAddress(IEnumerable ip, IEnumerable submask, IEnumerable getway, IEnumerable dns)
        {
            var wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var moc = wmi.GetInstances();
            foreach (var o in moc)
            {
                var mo = (ManagementObject) o;
                if (!(bool)mo["IPEnabled"])
                    continue;
                if (NetworkInterfaceId != mo["SettingID"].ToString()) continue;
                ManagementBaseObject inPar;
                ManagementBaseObject outPar;
                string str = null;
                if (ip != null && submask != null)
                {
                    inPar = mo.GetMethodParameters("EnableStatic");
                    inPar["IPAddress"] = ip;
                    inPar["SubnetMask"] = submask;
                    outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                    if (outPar != null) str = outPar["returnvalue"].ToString();
                    return (str=="0"||str=="1");
                    //获取操作设置IP的返回值, 可根据返回值去确认IP是否设置成功。 0或1表示成功
                }
                if(getway!=null)
                {
                    inPar = mo.GetMethodParameters("SetGateways");
                    inPar["DefaultIPGateway"] = getway;
                    outPar = mo.InvokeMethod("SetGateways", inPar, null);
                    if (outPar != null) str = outPar["returnvalue"].ToString();
                    return (str == "0" || str == "1");
                }
                if (dns == null) continue;
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = dns;
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                if (outPar != null) str = outPar["returnvalue"].ToString();
                return (str == "0" || str == "1");
            }
            return false;
        }

   

推荐阅读:
  1. C# 操作MongoDB
  2. c# 关于string的必备操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

网络操作

上一篇:Linux系统Mysql编译安装配置

下一篇:c++程序真正的入口函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》