Change adapter setting from dynamic to static

ぃ、小莉子 提交于 2019-12-13 02:55:05

问题


I've seen a lot of code that allows me to set the IP address of a local workstation, but it only works if the workstation already has a static IP address. I need to change the adapter settings from obtaining an IP address automatically to using a static IP I give it.

The code I'm using now is below. It fails on the first if statement for every objMO. I know at least one adapter has IPv4 enbled (I can see it in the Network and Sharing Center), but, like I said, it is set to obtain the IP address automatically:

protected static void ChangeIPAndSubnet( IPAddress ipToSet, IPAddress subnetToSet )
{
    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMC.GetInstances();

    // change the IP for all active ManagementObjects
    foreach (ManagementObject objMO in objMOC)
    {
        if ((bool)objMO["IPEnabled"])
        {
            try
            {
                ManagementBaseObject setIP;
                ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");

                // it's too bad that we have nice, neat ip addresses to use, only to change them
                // back to strings, but that's how this code works
                string ip_address = ipToSet.ToString();
                string subnet_mask = subnetToSet.ToString();

                newIP["IPAddress"] = new string[] { ip_address };
                newIP["SubnetMask"] = new string[] { subnet_mask };

                setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
            }
            catch (Exception)
            {
                // report error
                string strError = "The IP Address and/or Subnet mask could not be changed.\n";
                strError += "Please check the values and try again";
                MessageBox.Show(strError, "Settings Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

How do I change the adapter settings to use an IP address (and subnet mask) I give it?

来源:https://stackoverflow.com/questions/16864698/change-adapter-setting-from-dynamic-to-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!