C# 修改IP、网关、DNS
时间: 2023-12-03 14:02:10 浏览: 161
要在C#中修改IP、网关和DNS,您可以使用WMI(Windows Management Instrumentation)类来实现。以下是示例代码:
```csharp
using System.Management;
public static void SetIP(string ipAddress, string subnetMask, string gateway, string dns)
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
try
{
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { ipAddress };
newIP["SubnetMask"] = new string[] { subnetMask };
mo.InvokeMethod("EnableStatic", newIP, null);
ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
mo.InvokeMethod("SetGateways", newGateway, null);
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = new string[] { dns };
mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch (Exception ex)
{
// Handle exception here
}
}
}
}
```
然后您可以调用该方法并传入所需的参数来修改IP、网关和DNS。例如:
```csharp
SetIP("192.168.1.100", "255.255.255.0", "192.168.1.1", "8.8.8.8");
```
这将把IP地址设置为192.168.1.100,子网掩码设置为255.255.255.0,网关设置为192.168.1.1,DNS设置为8.8.8.8。请注意,此代码需要管理员权限才能运行。
阅读全文