我想在下面使用此代码以编程方式更改我的IP地址,但我不知道networkInterfaceName(作为参数)的名称。我如何获得它?无论如何,networkInterfaceName代表什么?
public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)
{
var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
var ipProperties = networkInterface.GetIPProperties();
var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork);
var currentIPaddress = ipInfo.Address.ToString();
var currentSubnetMask = ipInfo.IPv4Mask.ToString();
var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;
if (!isDHCPenabled && currentIPaddress == ipAddress && currentSubnetMask == subnetMask)
return true; // no change necessary
var process = new Process
{
StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" static {ipAddress} {subnetMask}" + (string.IsNullOrWhiteSpace(gateway) ? "" : $"{gateway} 1")) { Verb = "runas" }
};
process.Start();
var successful = process.ExitCode == 0;
process.Dispose();
return successful;
}
答案 0 :(得分:1)
如果要获取正确的接口名称,则应从Microsoft文档NetworkInterface Class 阅读文章,从这里开始。
您可以仅从上述站点实现一些代码片段,然后在SetIP
方法中选择适当的接口,而不是从方法参数中获取它。如果您需要获得参数,它也应该非常简单。您有很多属性可以识别您感兴趣的网络接口。