0

I'm working on a tool for work that needs to reset the PC IP address to a specific IP and subnet mask.

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#).

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.

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


            }
        }
    }
Community
  • 1
  • 1
steelfeathers
  • 31
  • 1
  • 6

2 Answers2

1

If you try this, you should obtain the reason for failure:

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

Tried by OP, with this result:

This gives me 2147749891 as a return value. Does that mean anything to you?

As Yury suggested make sure you have admin privileges and UAC is not stopping you. A quick search of that error resulted with:

WBEM_E_ACCESS_DENIED 2147749891 (0x80041003) Current user does not have permission to perform the action

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Drew
  • 43
  • 9
  • This gives me 2147749891 as a return value. Does that mean anything to you? – steelfeathers May 22 '15 at 18:05
  • 1
    As Yury suggested make sure you have admin privileges and UAC is not stopping you. A quick search of that error resulted with.. WBEM_E_ACCESS_DENIED 2147749891 (0x80041003) Current user does not have permission to perform the action – Drew May 22 '15 at 18:09
0

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

Remarks
.NET Framework Security
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.

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42