如何用C#设置本机IP地址
时间: 2023-07-04 19:17:52 浏览: 69
可以使用C#中的System.Net.NetworkInformation.NetworkInterface类和System.Net.NetworkInformation.IPAddressCollection类来设置本机IP地址。
首先需要获取本机的网络接口,可以通过以下代码实现:
```
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
```
然后可以遍历接口列表,找到需要设置的接口。假设我们要设置的是第一个接口,可以通过以下代码获取该接口的IP配置信息:
```
IPInterfaceProperties ipProperties = interfaces[0].GetIPProperties();
```
接下来,可以通过以下代码来设置IP地址:
```
UnicastIPAddressInformation ipInfo = ipProperties.UnicastAddresses[0];
IPAddress newIpAddress = IPAddress.Parse("192.168.0.100");
ipProperties.UnicastAddresses.Clear();
ipProperties.UnicastAddresses.Add(new UnicastIPAddressInformation(newIpAddress, ipInfo.IPv4Mask));
```
完整代码如下:
```
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
IPInterfaceProperties ipProperties = interfaces[0].GetIPProperties();
UnicastIPAddressInformation ipInfo = ipProperties.UnicastAddresses[0];
IPAddress newIpAddress = IPAddress.Parse("192.168.0.100");
ipProperties.UnicastAddresses.Clear();
ipProperties.UnicastAddresses.Add(new UnicastIPAddressInformation(newIpAddress, ipInfo.IPv4Mask));
```
需要注意的是,设置IP地址需要有管理员权限。