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