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

C#獲取設置IP地址,啟用禁用適配器,

編輯:C#入門知識

C#獲取設置IP地址,啟用禁用適配器,


界面效果圖如下: 

報表界面

 

說下關鍵代碼

 需要開啟 Windows Management Instrumentation服務(默認已經開啟),在程序中需要增加 Management引用。

主要有NetworkAdapter(保存適配器的IP地址,網關,子網掩碼,設置IP方面等 ),NetworkAdapterUtil(主要是NetworkAdapter類的集合 )兩個類。

 在windows8 需要在app.manifest文件中 

修改配置  <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,不然就算有管理員權限也修改不了IP地址。

1 設置IP地址的代碼。(設置IP地址,修改IP地址需要管理員權限)

    /// <summary>
    /// 網絡適配器類
    /// </summary>
    public class NetworkAdapter
    { 

/// <summary>
        /// 設置IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        /// <param name="dns"></param>
        private bool SetIPAddress(string[] ip, string[] submask, string[] getway, string[] dns)
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            string str = "";
            foreach (ManagementObject mo in moc)
            {

                if (!(bool)mo["IPEnabled"])
                    continue;

              
                if (this.NetworkInterfaceID == mo["SettingID"].ToString())
                {
                    if (ip != null && submask != null)
                    {
                        string caption = mo["Caption"].ToString(); //描述
                        inPar = mo.GetMethodParameters("EnableStatic");
                        inPar["IPAddress"] = ip;
                        inPar["SubnetMask"] = submask;
                        outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                        str = outPar["returnvalue"].ToString();
                        return (str=="0"||str=="1")?true:false;
                         //獲取操作設置IP的返回值, 可根據返回值去確認IP是否設置成功。 0或1表示成功 
                        // 返回值說明網址: https://msdn.microsoft.com/en-us/library/aa393301(v=vs.85).aspx
                    }
                    if(getway!=null)
                    {
                        inPar = mo.GetMethodParameters("SetGateways");
                        inPar["DefaultIPGateway"] = getway;
                        outPar = mo.InvokeMethod("SetGateways", inPar, null);
                        str = outPar["returnvalue"].ToString();
                        return (str == "0" || str == "1") ? true : false;
                    }
                    if (dns != null)
                    {
                        inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        inPar["DNSServerSearchOrder"] = dns;
                        outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                        str = outPar["returnvalue"].ToString();
                        return (str == "0" || str == "1") ? true : false;
                    }
                   
                }
            }
            return false;
        } 
}

2 設置IP為自動獲取

     /// <summary>
        /// 啟用DHCP服務
        /// </summary>
        public void EnableDHCP()
        {

            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;

                if (mo["SettingID"].ToString() == this.NetworkInterfaceID) //網卡接口標識是否相等, 相當只設置指定適配器IP地址
                {
                    mo.InvokeMethod("SetDNSServerSearchOrder", null);
                    mo.InvokeMethod("EnableDHCP", null);

                }
            }
        }

 

  3. 獲取所有適配器

public class NetworkAdapterUtil
{


 /// <summary>
       /// 獲取所有適配器類型,適配器被禁用則不能獲取到
       /// </summary>
       /// <returns></returns>
       public List<NetworkAdapter> GetAllNetworkAdapters() //如果適配器被禁用則不能獲取到
       {
           IEnumerable<NetworkInterface> adapters = NetworkInterface.GetAllNetworkInterfaces(); //得到所有適配器
           return GetNetworkAdapters(adapters);

       }

 /// <summary>
      /// 根據條件獲取IP地址集合,
      /// </summary>
       /// <param name="adapters">網絡接口地址集合</param>
      /// <param name="adapterTypes">網絡連接狀態,如,UP,DOWN等</param>
      /// <returns></returns>
       private List<NetworkAdapter> GetNetworkAdapters(IEnumerable<NetworkInterface> adapters, params NetworkInterfaceType[] networkInterfaceTypes)
        {
            adapterList = new List<NetworkAdapter>();

            foreach (NetworkInterface adapter in adapters)
            {
                if (networkInterfaceTypes.Length <=0) //如果沒傳可選參數,就查詢所有
                {
                    if (adapter != null)
                    {
                        NetworkAdapter adp = SetNetworkAdapterValue(adapter);
                        adapterList.Add(adp);
                    }
                    else
                    {
                        return null;
                    }
                }
                else //過濾查詢數據
                {
                   foreach (NetworkInterfaceType networkInterfaceType in networkInterfaceTypes) 
                    {                     
                       if (adapter.NetworkInterfaceType.ToString().Equals(networkInterfaceType.ToString())) 
                        {
                            adapterList.Add(SetNetworkAdapterValue(adapter)); 
                            break; //退出當前循環
                        }
                    }
                }
            }
            return adapterList;
        }

  /// <summary>
      /// 設置網絡適配器信息
      /// </summary>
      /// <param name="adapter"></param>
      /// <returns></returns>
      private NetworkAdapter SetNetworkAdapterValue(NetworkInterface adapter)
      {
          NetworkAdapter networkAdapter = new NetworkAdapter();
          IPInterfaceProperties ips = adapter.GetIPProperties();
          networkAdapter.Description = adapter.Name;
          networkAdapter.NetworkInterfaceType = adapter.NetworkInterfaceType.ToString();
          networkAdapter.Speed = adapter.Speed / 1000 / 1000 + "MB"; //速度
          networkAdapter.MacAddress = adapter.GetPhysicalAddress(); //物理地址集合
          networkAdapter.NetworkInterfaceID = adapter.Id;//網絡適配器標識符

          networkAdapter.Getwaryes = ips.GatewayAddresses; //網關地址集合
          networkAdapter.IPAddresses = ips.UnicastAddresses; //IP地址集合
          networkAdapter.DhcpServerAddresses = ips.DhcpServerAddresses;//DHCP地址集合
          networkAdapter.IsDhcpEnabled =ips.GetIPv4Properties()==null?false: ips.GetIPv4Properties().IsDhcpEnabled; //是否啟用DHCP服務

          IPInterfaceProperties adapterProperties = adapter.GetIPProperties();//獲取IPInterfaceProperties實例  
          networkAdapter.DnsAddresses = adapterProperties.DnsAddresses; //獲取並顯示DNS服務器IP地址信息 集合
          return networkAdapter;
      }
    }

  
}

4  啟用, 禁用適配器代碼 

       /// <summary>
       /// 啟用所有適配器
       /// </summary>
       /// <returns></returns>
       public void  EnableAllAdapters()
       {
          // ManagementClass wmi = new ManagementClass("Win32_NetworkAdapter");
          // ManagementObjectCollection moc = wmi.GetInstances();
           System.Management.ManagementObjectSearcher moc = new System.Management.ManagementObjectSearcher("Select * from Win32_NetworkAdapter where NetEnabled!=null ");     
           foreach (System.Management.ManagementObject mo in moc.Get())
           {
               //if (!(bool)mo["NetEnabled"])
               //    continue;
               string capation = mo["Caption"].ToString();
               string descrption =mo["Description"].ToString();
               mo.InvokeMethod("Enable",null);
           }
          
       }

       /// <summary>
       /// 禁用所有適配器
       /// </summary>
       public void DisableAllAdapters()
       {
           // ManagementClass wmi = new ManagementClass("Win32_NetworkAdapter");
           // ManagementObjectCollection moc = wmi.GetInstances();
           System.Management.ManagementObjectSearcher moc = new System.Management.ManagementObjectSearcher("Select * from Win32_NetworkAdapter where NetEnabled!=null ");
           foreach (System.Management.ManagementObject mo in moc.Get())
           {
               //if ((bool)mo["NetEnabled"])
               //    continue;
               string capation = mo["Caption"].ToString();
               string descrption = mo["Description"].ToString();
               mo.InvokeMethod("Disable", null);
           }

       }

 

程序下載地址: http://download.csdn.net/detail/ss641135196/8808159 

 

  在寫程序中參考網址:

https://msdn.microsoft.com/en-us/library/aa394084(VS.85).aspx WMI 管網

 http://www.cnblogs.com/chengulv/archive/2012/12/29/2839303.html 參考網址

http://blog.sina.com.cn/s/blog_64b9c6850100h6r9.html

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved