Reputation: 379
I want to use this code below to change my ip address programmatically, but i do not know the name of networkInterfaceName(as parameter).How can i get it? What does networkInterfaceName represent anyway?
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;
}
Upvotes: 1
Views: 4479
Reputation: 4130
Below code worked for me in Windows 11:
public void setIPAddress() {
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C netsh interface ip set address name=Ethernet static 192.168.5.10 255.255.255.0 192.168.5.1";
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();
}
Upvotes: 0
Reputation: 760
If you want to obtain proper interface name, you should start here, reading article from Microsoft docs: NetworkInterface Class .
You can just implement some code snippets from above site and choose proper interface in your SetIP
method instead getting it from method parameter. If you need to get it in paramter, it should be also very simple. You have lot of properties to identify network interface you interested in.
Upvotes: 1