0

我见过很多代码可以让我设置本地工作站的 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 地址(和子网掩码)?

4

0 回答 0