如何用C#设置本机IP地址
时间: 2023-07-04 09:17:28 浏览: 149
以下是一个简单的C#代码示例,用于设置本机IP地址和子网掩码:
```
using System.Net;
using System.Net.NetworkInformation;
IPAddress newIpAddress = IPAddress.Parse("192.168.1.100");
IPAddress subnetMask = IPAddress.Parse("255.255.255.0");
string networkInterfaceName = "Ethernet";
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in networkInterfaces)
{
if (networkInterface.Name == networkInterfaceName)
{
IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
UnicastIPAddressInformationCollection unicastAddresses = ipProperties.UnicastAddresses;
foreach (UnicastIPAddressInformation address in unicastAddresses)
{
if (address.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipProperties.UnicastAddresses.Remove(address);
break;
}
}
ipProperties.UnicastAddresses.Add(new UnicastIPAddressInformation(newIpAddress, subnetMask));
networkInterface.SetIPProperties(ipProperties);
break;
}
}
```
此代码将更改名为“Ethernet”的网络接口的IP地址和子网掩码。请注意,更改本机IP地址需要管理员权限。
阅读全文