我正在使用自定義DHCP協議獲取IP的一段代碼。代碼然後需要將其中一臺機器NIC設置爲該IP。在Windows 7上設置計算機IP
我的代碼如下。
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();
}
我繼續在EnableStatic調用上獲取2147749891。這篇文章Machine IP reset does nothing表明我需要管理員權限在我所做的機器上。
微軟頁面https://msdn.microsoft.com/en-us/library/aa390383(v=vs.85).aspx表明我需要獲得一個寫鎖,它需要我想避免的com代碼。
有沒有更好的方式來實現這一點,也許使用netsh,並可能以不需要管理員權限的方式?我所有的網卡的MAC地址來設置和細節設置它
感謝