简体   繁体   English

机器IP重置不执行任何操作

[英]Machine IP reset does nothing

I'm working on a tool for work that needs to reset the PC IP address to a specific IP and subnet mask. 我正在使用的工具需要将PC IP地址重置为特定的IP和子网掩码。

I've used the code below to try to change the IP (taken from this page: How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C# ). 我使用下面的代码尝试更改IP(从此页面获取: 如何使用C#中的代码更改网络设置(IP地址,DNS,WINS,主机名) )。

The problem is, this code doesn't do anything. 问题是,此代码不执行任何操作。 The IP address of my computer's local connection doesn't change - it's still being automatically set via DHCP. 我计算机的本地连接的IP地址没有更改-仍通过DHCP自动设置。

Help? 救命?

public void SetIP(string ip_address, string subnet_mask)
    {

        ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection objMOC = objMC.GetInstances();

        foreach (ManagementObject objMO in objMOC)
        {
            if ((bool)objMO["IPEnabled"])
            {
                try
                {
                    ManagementBaseObject setIP;
                    ManagementBaseObject newIP =
                        objMO.GetMethodParameters("EnableStatic");

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

                    setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
                }
                catch (Exception)
                {
                    throw;
                }


            }
        }
    }

If you try this, you should obtain the reason for failure: 如果尝试此操作,则应了解失败的原因:

MessageBox.Show("ReturnValue : " + setIP["ReturnValue"].ToString());

Tried by OP, with this result: 经过OP的尝试,结果如下:

This gives me 2147749891 as a return value. 这给我2147749891作为返回值。 Does that mean anything to you? 这对您有什么意义吗?

As Yury suggested make sure you have admin privileges and UAC is not stopping you. 如Yury所建议,请确保您具有管理员权限,并且UAC不会阻止您。 A quick search of that error resulted with: 快速搜索该错误导致:

WBEM_E_ACCESS_DENIED 2147749891 (0x80041003) Current user does not have permission to perform the action WBEM_E_ACCESS_DENIED 2147749891(0x80041003)当前用户无权执行操作

So, as we figured out so far, the main reason is lack of privileges. 因此,正如我们到目前为止所发现的,主要原因是缺乏特权。 As MSDN says about ManagementObject.InvokeMethod(), you need to be in fully-trusted execution scope: https://msdn.microsoft.com/en-us/library/ssk42c11(v=vs.110).aspx 正如MSDN关于ManagementObject.InvokeMethod()所说,您需要处于完全受信任的执行范围内: https : //msdn.microsoft.com/zh-cn/library/ssk42c11(v=vs.110).aspx

Remarks 备注
.NET Framework Security .NET Framework安全性
Full trust for the immediate caller. 完全信任直接调用方。 This member cannot be used by partially trusted code. 该成员不能由部分信任的代码使用。

So indeed you have to run this snippet under admin or analogous account. 因此,实际上您必须在admin或类似帐户下运行此代码段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM