C# 修改IP、网关、DNS
时间: 2023-12-03 11:02:23 浏览: 113
你可以使用C#中的System.Net.NetworkInformation命名空间中的类来修改IP、网关和DNS。首先,需要获取当前网络接口的配置信息,然后可以使用NetworkInterface类来修改配置信息。
以下是一个基本的示例代码:
```csharp
using System.Net;
using System.Net.NetworkInformation;
public void ModifyNetworkConfiguration(string ipAddress, string subnetMask, string gateway, string dns)
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
IPInterfaceProperties ipProps = ni.GetIPProperties();
UnicastIPAddressInformationCollection unicastAddresses = ipProps.UnicastAddresses;
foreach (UnicastIPAddressInformation address in unicastAddresses)
{
if (address.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ipAddress != null)
{
ipProps.UnicastAddresses.Clear();
ipProps.UnicastAddresses.Add(new UnicastIPAddressInformation(IPAddress.Parse(ipAddress), IPAddress.Parse(subnetMask)));
}
if (gateway != null)
{
ipProps.GatewayAddresses.Clear();
ipProps.GatewayAddresses.Add(new GatewayIPAddressInformation(IPAddress.Parse(gateway)));
}
if (dns != null)
{
ipProps.DnsAddresses.Clear();
ipProps.DnsAddresses.Add(IPAddress.Parse(dns));
}
ni.SetIPProperties(ipProps);
}
}
}
}
}
```
在上面的代码中,我们首先获取所有网络接口。然后,我们循环遍历每个接口,找到第一个IPv4地址,然后根据传入的参数修改IP地址、子网掩码、网关和DNS地址。最后,我们调用SetIPProperties方法来应用新的配置。
阅读全文