0

I am working on a bit of code that uses a custom DHCP protocol to get an ip. The code then needs to set one of the machines NICs to that ip.

The code i have for that is below.

    private void SetIp(IPAddress ipAddress, IPAddress subnetMask, IPAddress gatewayAddress)
    {
            try
            {
                ManagementBaseObject objNewIP = null;
                ManagementBaseObject objSetIP = null;
                ManagementBaseObject objNewGate = null;


                objNewIP = networkInterface.GetMethodParameters("EnableStatic");
                objNewGate = networkInterface.GetMethodParameters("SetGateways");



                //Set DefaultGateway
                objNewGate["DefaultIPGateway"] = new string[] { gatewayAddress.ToString() };
                objNewGate["GatewayCostMetric"] = new int[] { 1 };


                //Set IPAddress and Subnet Mask
                objNewIP["IPAddress"] = new string[] { ipAddress.ToString() };
                objNewIP["SubnetMask"] = new string[] { subnetMask.ToString() };

                objSetIP = networkInterface.InvokeMethod("EnableStatic", objNewIP, null);
                objSetIP = networkInterface.InvokeMethod("SetGateways", objNewGate, null);



                Console.WriteLine(
                   "Updated IPAddress, SubnetMask and Default Gateway!");



            }
            catch (Exception ex)
            {
            }

        // throw new System.NotImplementedException();
    }

I keep on getting 2147749891 on the EnableStatic call. This post Machine IP reset does nothing suggests i need admin priviledges on the machine which I do.

The microsoft page https://msdn.microsoft.com/en-us/library/aa390383(v=vs.85).aspx suggests i need to acquire a write lock which requires com code which i would rather avoid.

Is there a better way to achieve this, perhaps using netsh and maybe in a way that doesn't require admin priviledges? All i have the mac address of the NIC to set and the details to set for it

Thanks

Bernard
  • 995
  • 2
  • 9
  • 20

1 Answers1

1

I got the same error when calling EnableStatic.

Elevating the running user to an admin (run as admin) solved my problem, which seems normal: only admin can change the NIC parameters.

I have yet to determine why a user with admin access cannot run the same code, possibly an UAC problem, investigation is on-going.

As for the microsoft page (https://msdn.microsoft.com/en-us/library/aa390383(v=vs.85).aspx), the "Write lock not enabled" is 2147786788. Not 2147749891.

Vincent S
  • 11
  • 3