如何用C#设置本机固定IP地址
时间: 2023-07-04 11:17:52 浏览: 135
可以通过以下代码在C#中设置本机的固定IP地址:
```csharp
using System;
using System.Management;
public static void SetStaticIP(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"])
{
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { ipAddress };
newIP["SubnetMask"] = new string[] { subnetMask };
ManagementBaseObject setIP = null;
setIP = mo.InvokeMethod("EnableStatic", newIP, null);
ManagementBaseObject newGate = mo.GetMethodParameters("SetGateways");
newGate["DefaultIPGateway"] = new string[] { gateway };
ManagementBaseObject setGate = null;
setGate = mo.InvokeMethod("SetGateways", newGate, null);
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = new string[] { dns };
ManagementBaseObject setDNS = null;
setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
```
其中,`ipAddress`为要设置的IP地址,`subnetMask`为子网掩码,`gateway`为网关地址,`dns`为DNS服务器地址。在调用该方法后,本机的IP地址将会被设置为指定的固定IP地址。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)