C # Call WMI to change the local network IP settings

Source: Internet
Author: User

The following is a small program interface for changing the network IP interface based on the above ipprovider.

Because the network configuration is different between the home and the company, and I bring my notebook back and forth with the company at home. this leads to frequent setting of different IP addresses and gateway data. After a while, I felt very annoyed as a programmer. why don't we take advantage of our knowledge to get lazy? Especially a lazy person like me...

Because the network IP settings involve hardware, C # does not have a ready-made interface to call. we can only call the API or WMI. This system provides a bridge for us .. in the WMI library, the management class "win32_networkadapterconfiguration" is used to manage network configurations. the IP address, DNS, and gateway settings are basically included here...

It is easy to Use WMI in C. the C # implementation code is provided below. Haha, my text expression capability is poor, so I will not talk much about it. The amount of code is very small and it should look very simple:

Copy and save
UsingSystem;UsingSystem. collections;UsingSystem. text;UsingSystem. Management;UsingSystem. Text. regularexpressions;NamespaceKingthy. Windows. ipchanger. Providers {/// <Summary>    /// Summary of ipprovider.    /// </Summary>    Public ClassIpprovider {PublicIpprovider (){//            // Todo: add the constructor logic here            //}/// <Summary>        /// Set DNS        /// </Summary>        /// <Param name = "DNS"> </param>        Public Static VoidSetdns (String[] DNS) {setipaddress (Null,Null,Null, DNS );}/// <Summary>        /// Configure the Gateway        /// </Summary>        /// <Param name = "getway"> </param>        Public Static VoidSetgetway (StringGetway) {setipaddress (Null,Null,New String[] {Getway },Null);}/// <Summary>        /// Configure the Gateway        /// </Summary>        /// <Param name = "getway"> </param>        Public Static VoidSetgetway (String[] Getway) {setipaddress (Null,Null, Getway,Null);}/// <Summary>        /// Set the IP address and mask        /// </Summary>        /// <Param name = "ip"> </param>        /// <Param name = "submask"> </param>        Public Static VoidSetipaddress (StringIP,StringSubmask) {setipaddress (New String[] {IP },New String[] {Submask },Null,Null);}/// <Summary>        /// Set the IP address, mask, and gateway        /// </Summary>        /// <Param name = "ip"> </param>        /// <Param name = "submask"> </param>        /// <Param name = "getway"> </param>        Public Static VoidSetipaddress (StringIP,StringSubmask,StringGetway) {setipaddress (New String[] {IP },New String[] {Submask },New String[] {Getway },Null);}/// <Summary>        /// Set the IP address, mask, gateway, and DNS        /// </Summary>        /// <Param name = "ip"> </param>        /// <Param name = "submask"> </param>        /// <Param name = "getway"> </param>        /// <Param name = "DNS"> </param>        Public Static VoidSetipaddress (String[] IP,String[] Submask,String[] Getway,String[] DNS) {managementclass WMI =NewManagementclass ("Win32_networkadapterconfiguration"); Managementobjectcollection MOC = WMI. getinstances (); managementbaseobject inpar =Null; Managementbaseobject outpar =Null;Foreach(Managementobject MoInMOC ){// Skip this step if no network device with IP settings Enabled                If(! (Bool) Mo ["Ipenabled"])Continue;// Set the IP address and mask                If(IP! =Null& Submask! =Null) {Inpar = Mo. getmethodparameters ("Enablestatic"); Inpar ["IPaddress"] = IP; inpar ["Subnetmask"] = Submask; outpar = Mo. invokemethod ("Enablestatic", Inpar,Null);}// Set the gateway address                If(Getway! =Null) {Inpar = Mo. getmethodparameters ("Setgateways"); Inpar ["Defaultipgateway"] = Getway; outpar = Mo. invokemethod ("Setgateways", Inpar,Null);}// Set the DNS address                If(DNS! =Null) {Inpar = Mo. getmethodparameters ("Setdnsserversearchorder"); Inpar ["Dnsserversearchorder"] = DNS; outpar = Mo. invokemethod ("Setdnsserversearchorder", Inpar,Null);}}}/// <Summary>        /// Enable the DHCP server        /// </Summary>        Public Static VoidEnabledhcp () {managementclass WMI =NewManagementclass ("Win32_networkadapterconfiguration"); Managementobjectcollection MOC = WMI. getinstances ();Foreach(Managementobject MoInMOC ){// Skip this step if no network device with IP settings Enabled                If(! (Bool) Mo ["Ipenabled"])Continue;// Reset DNS to nullMo. invokemethod ("Setdnsserversearchorder",Null);// Enable DHCPMo. invokemethod ("Enabledhcp",Null);}}/// <Summary>        /// Determine whether the IP address format is correct        /// </Summary>        /// <Param name = "ip"> </param>        /// <Returns> </returns>        Public Static BoolIsipaddress (StringIP ){String[] Arr = IP. Split ('.');If(ARR. length! = 4)Return False;StringPattern =@ "\ D {1, 3 }";For(IntI = 0; I <arr. length; I ++ ){StringD = arr [I];If(I = 0 & D ="0")Return False;If(! RegEx. ismatch (D, pattern ))Return False;If(D! ="0") {D = D. trimstart ('0');If(D ="")Return False;If(Int. Parse (d)> 255)Return False;}}Return True;}}}
【Reprinted from :http://www.chenjiliang.com/Article/View.aspx?ArticleID=3860&TypeID=84】

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.