程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#的網絡適配器操作,

C#的網絡適配器操作,

編輯:C#入門知識

C#的網絡適配器操作,


     網絡的相關設置在項目開發中有較多的應用,有時候需要在項目中對網絡信息進行相關設置。

     現在提供提供幾種相關的輔助方法類。

(1).IP地址

        /// <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)); }
        }

(2).網關地址

        /// <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)); }
        }

(3). DHCP服務器地址

       /// <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)); }
        }

(4).MAC地址

        /// <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)); }
        }

(5). 主DNS地址

        /// <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)); }
        }

(6).備用DNS地址

        /// <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)); }
        }

(7).子網掩碼

        /// <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)); }
        }

(8).屬性

       /// <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; } 

(9).是否是IP地址

        /// <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;
        }

(10).啟用DHCP服務

        /// <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;
        }

(11).設置IP地址,子網掩碼,網關,DNS

        /// <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);

        }

(12).設置主,備份DNS地址

        /// <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);

        }

(13).得到IPV4地址

        /// <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];
        }

(14).檢查設置IP地址,如果返回空,表示檢查通過,為了方便返回就字符串了

        /// <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地址格式不對" : "";
        }

(15).設置IP地址

        /// <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. 上一頁:
  2. 下一頁: