C # Get the configured IP address, enable the disabled adapter,

Source: Internet
Author: User

C # Get the configured IP address, enable the disabled adapter,

The interface is as follows:

Report page

 

Let's talk about the key code.

To enable the Windows Management Instrumentation Service (enabled by default), add a Management reference to the program.

NetworkAdapter (Save the IP address of the adapter, gateway, subnet mask, set IP address, etc.) and NetworkAdapterUtil (mainly a set of NetworkAdapter classes.

In Windows 8, you must go to the app. manifest file.

Modify the configuration <requestedExecutionLevel level = "requireAdministrator" uiAccess = "false"/>. Otherwise, the IP address cannot be modified even if you have the Administrator permission.

1. IP Address Setting code. (Set the IP address. administrator privilege is required to modify the IP address)

/// <Summary> /// network adapter class /// </summary> public class NetworkAdapter {// <summary> /// set the IP address /// </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_NetworkAdapterConfigur Ation "); 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 (); // description 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; // obtain the return value of the IP address set by the operation. You can confirm whether the IP address is set successfully based on the returned value. 0 or 1 indicates success // return value URL: 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. Set the IP address to automatically get

/// <Summary> /// enable DHCP service /// </summary> public void EnableDHCP () {ManagementClass wmi = new ManagementClass ("win32network_adapterconfiguration "); managementObjectCollection moc = wmi. getInstances (); foreach (ManagementObject mo in moc) {if (! (Bool) mo ["IPEnabled"]) continue; if (mo ["SettingID"]. toString () = this. networkInterfaceID) // whether the NIC Interface ID is equal. Only the specified adapter IP address {mo. invokeMethod ("SetDNSServerSearchOrder", null); mo. invokeMethod ("EnableDHCP", null );}}}

 

3. Get all adapters

Public class NetworkAdapterUtil {// <summary> // obtain all the adapter types, if the adapter is disabled, it cannot be obtained. // </summary> // <returns> </returns> public List <NetworkAdapter> GetAllNetworkAdapters () // If the adapter is disabled, {IEnumerable <NetworkInterface> adapters = NetworkInterface cannot be obtained. getAllNetworkInterfaces (); // get all the adapters return GetNetworkAdapters (adapters);} // <summary> // obtain the IP address set based on the conditions, /// </summary> /// <param name = "adapters"> network interface address set </Param> // <param name = "adapterTypes"> network connection status, such as UP, </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 no optional parameter is input, query all {if (adapter! = Null) {NetworkAdapter adp = SetNetworkAdapterValue (adapter); adapterList. add (adp) ;}else {return null ;}} else // filter query data {foreach (NetworkInterfaceType networkInterfaceType in networkInterfaceTypes) {if (adapter. networkInterfaceType. toString (). equals (networkInterfaceType. toString () {adapterList. add (SetNetworkAdapterValue (adapter); break; // exit the current loop }}} return adapterList;} // <summar Y> // set network adapter information /// </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 (); netw OrkAdapter. speed = adapter. speed/1000/1000 + "MB"; // Speed networkAdapter. macAddress = adapter. getPhysicalAddress (); // a set of physical addresses networkAdapter. networkInterfaceID = adapter. id; // network adapter identifier networkAdapter. getwaryes = ips. gatewayAddresses; // The networkAdapter of the gateway address set. IPAddresses = ips. unicastAddresses; // ip address set networkAdapter. dhcpServerAddresses = ips. dhcpServerAddresses; // DHCP address set networkAdapter. isDhcpEnab Led = ips. GetIPv4Properties () = null? False: ips. getIPv4Properties (). isDhcpEnabled; // whether to enable the DHCP service IPInterfaceProperties adapterProperties = adapter. getIPProperties (); // obtain the networkAdapter of the IPInterfaceProperties instance. dnsAddresses = adapterProperties. dnsAddresses; // get and display the DNS server IP address information set return networkAdapter ;}}}

4. Enable and disable the adapter code

/// <Summary> /// enable all adapters /// </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 >/// disable all adapters /// </summary> public void DisableAllAdapters () {// ManagementClass wmi = new ManagementClass ("Win32_NetworkAdapter"); // ManagementObjectCollection moc = wmi. getInstances (); System. management. managementObjec TSearcher 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 );}}

 

Program: http://download.csdn.net/detail/ss641135196/8808159

 

Refer to the URL for writing a program:

Https://msdn.microsoft.com/en-us/library/aa394084 (VS.85). aspx WMI Pipe Network

Http://www.cnblogs.com/chengulv/archive/2012/12/29/2839303.html Reference URL

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.