将适配器设置从动态更改为静态

时间:2013-05-31 19:41:01

标签: c# .net networking network-programming static-ip-address

我已经看到很多代码允许我设置本地工作站的IP地址,但它只有在工作站已经有静态IP地址时才有效。我需要将适配器设置从自动获取IP地址更改为使用我提供的静态IP。

我现在使用的代码如下。它在每个objMO的第一个if语句中失败。我知道至少有一个适配器有IPv4加密(我可以在网络和共享中心看到它),但是,就像我说的那样,它设置为自动获取IP地址:

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);
            }
        }
    }
}

如何更改适配器设置以使用我提供的IP地址(和子网掩码)?

0 个答案:

没有答案