C#设置Ip地址、网关、子网掩码。DNS
时间: 2023-08-04 20:06:21 浏览: 172
C#设置IP地址子网掩码默认网关DNS等参数
在C#中,可以使用以下代码设置IP地址、网关、子网掩码和DNS:
```csharp
using System.Management;
public static void SetIP(string ip, 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");
// Set IP address and subnet mask
newIP["IPAddress"] = new string[] { ip };
newIP["SubnetMask"] = new string[] { subnetMask };
mo.InvokeMethod("EnableStatic", newIP, null);
// Set default gateway
ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
mo.InvokeMethod("SetGateways", newGateway, null);
// Set DNS servers
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = dns;
mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch (Exception ex)
{
// Handle exceptions
}
}
}
}
```
其中,参数`ip`、`subnetMask`、`gateway`和`dns`分别为要设置的IP地址、子网掩码、网关和DNS服务器列表。注意,需要以管理员权限运行程序才能修改网络配置。
阅读全文