Search code examples
c#wmi

Problems using the WMI EnableStatic method


I'm trying to create a tool that converts the dynamic DHCP-provided IPv4 address, gateway and dns-settings into static configuration. I've tried to use WMI to solve this puzzle, but I have a problem I can't figure out.

The application completes, DNS and Gateway is configured, but the EnableStatic method (to set the IP address and subnet) has been unsuccesful which means that the IP is still received from DHCP (with greyed out fields) even though the default gateway has been set. How do I fix this?

The ReturnValue from EnableStatic is 70 (Invalid IP address). The weird thing is that the input parameters are the same that I extracted from the NIC 2 seconds earlier.

Here is the code (except GUI), http://pastebin.com/AE3dGhUz:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;

namespace Static_NIC_Settings_Creator
{
    public partial class Form1 : Form
    {
        private ManagementObjectCollection queryCollection;
        private string[] networkInterfaces;
        private int currentNIC;
        private string[] ipAddress;
        private string[] subnetMask;
        private string[] defaultIPGateway;
        private string[] dnsServerSearchOrder;

        public Form1()
        {
            InitializeComponent();
            getNICs();
        }

        private void convertButton_Click(object sender, EventArgs e)
        {
            if (networkInterfaces.Count() > 0)
            {
                //Get current NIC settings
                if (!getNICSettings())
                {
                    MessageBox.Show("Retrieving current NIC settings failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                //Convert to static NIC settings
                if (!setNICStatic())
                {
                    MessageBox.Show("Setting NIC settings to static failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }

        private void nicSelecter_SelectedIndexChanged(object sender, EventArgs e)
        {
            currentNIC = nicSelecter.SelectedIndex;
        }

        private void getNICs()
        {
            //Get NICS
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            queryCollection = query.Get();
            //Make nic string array
            int i = queryCollection.Count;
            networkInterfaces = new string[i];
            //Fill nic string array
            i = 0;
            foreach (ManagementObject mo in queryCollection)
            {
                networkInterfaces[i] = (String)mo["Description"];
                i++;
            }
            //Fill dropbox with arraylist-data
            nicSelecter.DataSource = networkInterfaces;
        }

        private Boolean getNICSettings()
        {
            //Get selected NIC
            int i = 0;
            foreach (ManagementObject mo in queryCollection)
            {
                //Get settings for specific NIC
                if (i == currentNIC)
                {
                    try
                    {
                        ipAddress = (String[])mo["IPAddress"];
                        subnetMask = (String[])mo["IPSubnet"];
                        defaultIPGateway = (String[])mo["DefaultIPGateway"];
                        dnsServerSearchOrder = (String[])mo["DNSServerSearchOrder"];
                        return true;
                    }
                    catch (Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show(e.ToString(), "Critical: Unhandled error");
                        return false;
                    }
                }
                i++;
            }
            return false;
        }

        private Boolean setNICStatic()
        {
            //Get selected NIC
            int i = 0;
            foreach (ManagementObject mo in queryCollection)
            {
                //Get settings for specific NIC
                if (i == currentNIC)
                {
                    try
                    {
                        //Set static IP and subnet mask
                        ManagementBaseObject setIP;
                        ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
                        newIP["IPAddress"] = ipAddress;
                        newIP["SubnetMask"] = subnetMask;
                        setIP = mo.InvokeMethod("EnableStatic", newIP, null);
                        //Set default gateway
                        ManagementBaseObject setGateway;
                        ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
                        newGateway["DefaultIPGateway"] = defaultIPGateway;
                        newGateway["GatewayCostMetric"] = new int[] { 1 };
                        setGateway = mo.InvokeMethod("SetGateways", newGateway, null);
                        //Set dns servers
                        ManagementBaseObject setDNS;
                        ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        newDNS["DNSServerSearchOrder"] = dnsServerSearchOrder;
                        setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);

                        System.Windows.Forms.MessageBox.Show("Setting NIC settings returned: " + setDNS);
                        return true;
                    }
                    catch (Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show(e.ToString(), "Critical: Unhandled error");
                        return false;
                    }
                }
                i++;
            }
            //No NICs
            return false;
        }
    } //End class
}

Any ideas?


Solution

  • Could it be that you are inputting IPv6 addresses as well? Just playing around with PowerShell it seems not to like them. Perhaps you can post actual values that are being inputted whilst debugging, it would help a lot. Also maybe try statically inputting some values like:

    new string[]{"192.168.0.1"}, new string[] {"255.255.255.255"}
    

    Also unless you really, really need C# and a GUI you may want to consider using PowerShell (requirement is it being installed of course) as WMI is really much simpler to manipulate there (sadly you still have that learning curve though).

    This is just an example of how to use PowerShell, you can at the very least use it for some testing:

    Get-WmiObject Win32_NetworkAdapterConfiguration
    

    Then get the index of your adapter then run, but replace your index number:

    $obj = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.Index -eq 1}
    $obj.EnableStatic("192.168.0.1", "255.255.255.0")
    

    To get method parameters just run:

    $obj.EnableStatic
    

    It will return:

    MemberType          : Method
    OverloadDefinitions : {System.Management.ManagementBaseObject EnableStatic(System.String[]IPAddress, System.String[] SubnetMask)}
    TypeNameOfValue     : System.Management.Automation.PSMethod
    Value               : System.Management.ManagementBaseObject EnableStatic(System.String[]IPAddress, System.String[] SubnetMask)
    Name                : EnableStatic
    IsInstance          : True