Adding an IP Address to a NIC card using c# [duplicate] - c#

I have an application written in C# that needs to be able to configure the network adapters in Windows. I have this basically working through WMI, but there are a couple of things I don't like about that solution: sometimes the settings don't seem to stick, and when the network cable is not plugged in, errors are returned from the WMI methods, so I can't tell if they really succeeded or not.
I need to be able to configure all of the settings available through the network connections - Properties - TCP/IP screens.
What's the best way to do this?

You could use Process to fire off netsh commands to set all the properties in the network dialogs.
eg:
To set a static ipaddress on an adapter
netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.1 1
To set it to dhcp you'd use
netsh interface ip set address "Local Area Connection" dhcp
To do it from C# would be
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();
Setting to static can take a good couple of seconds to complete so if you need to, make sure you wait for the process to exit.

With my code
SetIpAddress and SetDHCP
/// <summary>
/// Sets the ip address.
/// </summary>
/// <param name="nicName">Name of the nic.</param>
/// <param name="ipAddress">The ip address.</param>
/// <param name="subnetMask">The subnet mask.</param>
/// <param name="gateway">The gateway.</param>
/// <param name="dns1">The DNS1.</param>
/// <param name="dns2">The DNS2.</param>
/// <returns></returns>
public static bool SetIpAddress(
string nicName,
string ipAddress,
string subnetMask,
string gateway = null,
string dns1 = null,
string dns2 = null)
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
string nicDesc = nicName;
if (networkInterface != null)
{
nicDesc = networkInterface.Description;
}
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true
&& mo["Description"].Equals(nicDesc) == true)
{
try
{
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { ipAddress };
newIP["SubnetMask"] = new string[] { subnetMask };
ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
if (gateway != null)
{
ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
ManagementBaseObject setGateway = mo.InvokeMethod("SetGateways", newGateway, null);
}
if (dns1 != null || dns2 != null)
{
ManagementBaseObject newDns = mo.GetMethodParameters("SetDNSServerSearchOrder");
var dns = new List<string>();
if (dns1 != null)
{
dns.Add(dns1);
}
if (dns2 != null)
{
dns.Add(dns2);
}
newDns["DNSServerSearchOrder"] = dns.ToArray();
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
}
}
catch
{
return false;
}
}
}
return true;
}
/// <summary>
/// Sets the DHCP.
/// </summary>
/// <param name="nicName">Name of the nic.</param>
public static bool SetDHCP(string nicName)
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
string nicDesc = nicName;
if (networkInterface != null)
{
nicDesc = networkInterface.Description;
}
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true
&& mo["Description"].Equals(nicDesc) == true)
{
try
{
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch
{
return false;
}
}
}
return true;
}

with the help of #PaulB's answers help
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address " + nics[0].Name + " static 192.168." + provider_ip + "." + index + " 255.255.255.0 192.168." + provider_ip + ".1 1");
p.StartInfo = psi;
p.StartInfo.Verb = "runas";
p.Start();

I can tell you the way the trojans do it, after having had to clean up after a few of them, is to set registry keys under HKEY_LOCAL_MACHINE. The main ones they set are the DNS ones and that approach definitely sticks which can be attested to by anyone who has ever been infected and can no longer get to windowsupdate.com, mcafee.com, etc.

Checkout this app. it is a complete application to set both wifi and ethernet ips
https://github.com/kamran7679/ConfigureIP

Related

Create domain in windows Dns using C # [duplicate]

I need some sample code to create/delete zone and A record in microsoft DNS server by C#
You have to use WMI to invoke the DNSProvider.
This to add a record:
public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName)
{
ManagementScope scope =
new ManagementScope(#"\\" + dnsServerName + "\\root\\MicrosoftDNS");
scope.Connect();
ManagementClass cmiClass =
new ManagementClass(scope,
new ManagementPath("MicrosoftDNS_AType"),
null);
ManagementBaseObject inParams =
cmiClass.GetMethodParameters("CreateInstanceFromPropertyData");
inParams["DnsServerName"] = this.ServerName;
inParams["ContainerName"] = zone;
inParams["OwnerName"] = hostName + "." + zone;
inParams["IPAddress"] = iPAddress;
cmiClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null);
}
You can reference the WMI reference and extend this as you need using the methods and classes
http://msdn.microsoft.com/en-us/library/ms682123(v=vs.85).aspx
Microsoft exposes it as a POX service, so you could just push XML over the wire to it, using the System.Net stuff & your user credentials.
http://technet.microsoft.com/en-us/library/dd278634.aspx
I agreed with Taylor but in my case i have got 2 different error with above code
1- Generic Error
2- Not Found error
Below code has solved this problems
private ManagementPath UpdateARecord(string strDNSZone, string strHostName, string strIPAddress)
{
ManagementScope mgmtScope = new ManagementScope(#"\\.\Root\MicrosoftDNS");
ManagementClass mgmtClass = null;
ManagementBaseObject mgmtParams = null;
ManagementObjectSearcher mgmtSearch = null;
ManagementObjectCollection mgmtDNSRecords = null;
string strQuery;
strQuery = string.Format("SELECT * FROM MicrosoftDNS_AType WHERE OwnerName = '{0}.{1}'", strHostName, strDNSZone);
mgmtScope.Connect();
mgmtSearch = new ManagementObjectSearcher(mgmtScope, new ObjectQuery(strQuery));
mgmtDNSRecords = mgmtSearch.Get();
//// Multiple A records with the same record name, but different IPv4 addresses, skip.
//if (mgmtDNSRecords.Count > 1)
//{
// // Take appropriate action here.
//}
//// Existing A record found, update record.
//else
if (mgmtDNSRecords.Count == 1)
{
ManagementObject mo = new ManagementObject();
foreach (ManagementObject mgmtDNSRecord in mgmtDNSRecords)
{
if (mgmtDNSRecord["RecordData"].ToString() != strIPAddress)
{
mgmtParams = mgmtDNSRecord.GetMethodParameters("Modify");
mgmtParams["IPAddress"] = strIPAddress;
mgmtDNSRecord.InvokeMethod("Modify", mgmtParams, null);
}
mo = mgmtDNSRecord;
break;
}
return new ManagementPath(mo["RR"].ToString());
}
// A record does not exist, create new record.
else
{
mgmtClass = new ManagementClass(mgmtScope, new ManagementPath("MicrosoftDNS_AType"), null);
mgmtParams = mgmtClass.GetMethodParameters("CreateInstanceFromPropertyData");
mgmtParams["DnsServerName"] = Environment.MachineName;
mgmtParams["ContainerName"] = strDNSZone;
mgmtParams["OwnerName"] = strDNSZone;// string.Format("{0}.{1}", strHostName.ToLower(), strDNSZone);
mgmtParams["IPAddress"] = strIPAddress;
var outParams = mgmtClass.InvokeMethod("CreateInstanceFromPropertyData", mgmtParams, null);
if ((outParams.Properties["RR"] != null))
{
return new ManagementPath(outParams["RR"].ToString());
}
}
return null;
}

How to set IP address of device connected to Host PC? C# Winform?

I have a Modbus TCP/IP to MODBUS RTU converter , which comes with a default IP of 192.168.0.1 . I need to develop a small c# Winform app to change this device's IP address to any desired IP address. How do I do that?.
You could do it with WMI (Windows Management Instrumentation).
First, you have to add the reference for System.Management to your Project.
Second, you need to find the NetworkInterface for your network connection by name:
using System.Net.NetworkInformation;
using System.Management;
public class NetworkManager
{
public static NetworkInterface GetNetworkInterface(string sName)
{
NetworkInterface NetInterface = null;
// Precondition
if (sName == "") return null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.Name == sName)
{
NetInterface = ni;
break;
}
}
return NetInterface;
}
Third, you have to create a ManagementObject for your NetworkInterface:
public static ManagementObject GetNetworkAdapterManagementObject(NetworkInterface NetInterface)
{
ManagementObject oMngObj = null;
// Precondition
if (NetInterface == null) return null;
string sNI = NetInterface.Id;
ManagementClass oMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection oMOC = oMC.GetInstances();
foreach (ManagementObject oMO in oMOC)
{
string sMO = oMO["SettingID"].ToString();
if (sMO == sNI)
{
// Found
oMngObj = oMO;
break;
}
}
return oMngObj;
}
Fours, you can set the ipadress with:
public static bool SetIPAdress(ManagementObject oMO, string[] saIPAdress, string[] saSubnetMask)
{
bool bErg = false;
try
{
// Precondition
if (oMO == null) return false;
if (saIPAdress == null) return false;
if (saSubnetMask == null) return false;
// Get ManagementBaseObject
ManagementBaseObject oNewIP = null;
oNewIP = oMO.GetMethodParameters("EnableStatic");
oNewIP["IPAddress"] = saIPAdress;
oNewIP["SubnetMask"] = saSubnetMask;
// Invoke
oMO.InvokeMethod("EnableStatic", oNewIP, null);
// Alles ok
bErg = true;
}
catch (Exception ex)
{
Console.WriteLine("SetIPAdress failed: " + ex.Message);
}
return bErg;
}
}
Now you can use it, for example in a button click event handler:
private void button1_Click(object sender, EventArgs e)
{
string sConn = "LAN-Verbindung";
NetworkInterface oNI = NetworkManager.GetNetworkInterface(sConn);
ManagementObject oMO = NetworkManager.GetNetworkAdapterManagementObject(oNI);
string sIPAdress = "192.168.1.1";
string sSubnetMask = "255.255.255.0";
string[] saIPAdress = {sIPAdress};
string[] saSubnetMask = {sSubnetMask};
if (NetworkManager.SetIPAdress(oMO, saIPAdress, saSubnetMask))
{
Console.WriteLine("Yes...");
}
}
Depending on the policies on your pc, may be you have to run the program as Administrator...

Set ipv6 for windows with C#

I have a problem with set Ipv6 in windows.
The below code can set a IPv4 address but I can't try to set IPv6.
Please help me.
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
try
{
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
// Make sure this is a IP enabled device. Not something like memory card or VM Ware
if ((bool)mo["IPEnabled"])
{
if (mo["Caption"].Equals(nicName))
{
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
ManagementBaseObject newGate = mo.GetMethodParameters("SetGateways");
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newGate["DefaultIPGateway"] = new string[] { Gateway };
newGate["GatewayCostMetric"] = new int[] { 1 };
newIP["IPAddress"] = IpAddresses.Split(',');
newIP["SubnetMask"] = new string[] { SubnetMask };
newDNS["DNSServerSearchOrder"] = DnsSearchOrder.Split(',');
ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGate, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
break;
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
I also tried to set a fixed IPv6 address via WMI, but it does not appear to work (the IPv4 address does work).
The only way I found to do this is by starting netsh from within the code, and using it to set the fixed (static) IPv6 address. If anyone has a more elegant solution, I will happily use it. Meanwhile:
Use the .NET System.Diagnostics.Process class to start a netsh process.
The netsh command reference, which tells you the parameters that you need, is here.
I found that I needed to start a new netsh process for each command that I sent.
For each netsh process, I created a handler for the process's OutputDataReceived event, that logged the netsh feedback.

Change remote IP address programmatically using WMI

I am writing an application to change the IP addresses of local and remote machines using WMI. This code successfully changes the gateway and DNS of the remote machine and the same code (in a different class and minus the management scope part) changes all of the data (the two IPs, gateway, DNS) locally. The problem is it doesn't change the remote IP address. Please can someone advise as I have looked everywhere for this answer?
I have tested on windows 7 and xp with no firewalls and with .net 4 installed on remote machines
class remoteIPChange
{
public string setTillIP(string IPAddress1, string IPAddress2, string SubnetMask, string Gateway)
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:DOMAIN";
ManagementScope scope = new ManagementScope(
"\\\\"+IPAddress1+"\\root\\CIMV2", connection);
scope.Connect();
ObjectGetOptions o = new ObjectGetOptions();
ManagementPath p = new ManagementPath("Win32_NetworkAdapterConfiguration");
ManagementClass objMC = new ManagementClass(scope,p,o);
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
ManagementBaseObject objNewDNS = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] { Gateway };
objNewGate["GatewayCostMetric"] = new int[] { 1 };
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] { IPAddress1, IPAddress2 };
objNewIP["SubnetMask"] = new string[] { SubnetMask, SubnetMask };
//Set DNS servers
objNewDNS["DNSServerSearchOrder"] = new string[] {Gateway };
//Invoke all changes
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);
return ("Updated IPAddress to " + IPAddress + ", \nSubnetMask to " + SubnetMask + " \nand Default Gateway to " + Gateway + "!");
}
catch (Exception ex)
{
return ("Unable to Set IP : " + ex.Message);
}
}
return "code has not run";
}
}
I would check the ReturnValue from the invokemethod on EnableStatic. I am pretty sure passing in a null for your subnet is your problem. Provide a valid array of subnets that match your ip addresses instead of that null.

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

I am developing a wizard for a machine that is to be used as a backup of other machines. When it replaces an existing machine, it needs to set its IP address, DNS, WINS, and host name to match the machine being replaced.
Is there a library in .net (C#) which allows me to do this programatically?
There are multiple NICs, each which need to be set individually.
EDIT
Thank you TimothyP for your example. It got me moving on the right track and the quick reply was awesome.
Thanks balexandre. Your code is perfect. I was in a rush and had already adapted the example TimothyP linked to, but I would have loved to have had your code sooner.
I've also developed a routine using similar techniques for changing the computer name. I'll post it in the future so subscribe to this questions RSS feed if you want to be informed of the update. I may get it up later today or on Monday after a bit of cleanup.
Just made this in a few minutes:
using System;
using System.Management;
namespace WindowsFormsApplication_CS
{
class NetworkManagement
{
public void setIP(string ip_address, string subnet_mask)
{
ManagementClass objMC =
new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
ManagementBaseObject setIP;
ManagementBaseObject newIP =
objMO.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { ip_address };
newIP["SubnetMask"] = new string[] { subnet_mask };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
}
}
}
public void setGateway(string gateway)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
ManagementBaseObject setGateway;
ManagementBaseObject newGateway =
objMO.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
}
}
}
public void setDNS(string NIC, string DNS)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
// if you are using the System.Net.NetworkInformation.NetworkInterface
// you'll need to change this line to
// if (objMO["Caption"].ToString().Contains(NIC))
// and pass in the Description property instead of the name
if (objMO["Caption"].Equals(NIC))
{
ManagementBaseObject newDNS =
objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split(',');
ManagementBaseObject setDNS =
objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
public void setWINS(string NIC, string priWINS, string secWINS)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
if (objMO["Caption"].Equals(NIC))
{
ManagementBaseObject setWINS;
ManagementBaseObject wins =
objMO.GetMethodParameters("SetWINSServer");
wins.SetPropertyValue("WINSPrimaryServer", priWINS);
wins.SetPropertyValue("WINSSecondaryServer", secWINS);
setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);
}
}
}
}
}
}
Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I don't need to configure WINS anymore. Feel free to add the WINS code if you need it.
For the case anybody likes to use the refactored/modernized code I put it back into the community here.
/// <summary>
/// Helper class to set networking configuration like IP address, DNS servers, etc.
/// </summary>
public class NetworkConfigurator
{
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="ipAddress">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetIP(string ipAddress, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
{
using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
{
// Set new IP address and subnet if needed
if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
{
if (!String.IsNullOrEmpty(ipAddress))
{
newIP["IPAddress"] = new[] { ipAddress };
}
if (!String.IsNullOrEmpty(subnetMask))
{
newIP["SubnetMask"] = new[] { subnetMask };
}
managementObject.InvokeMethod("EnableStatic", newIP, null);
}
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
{
newGateway["DefaultIPGateway"] = new[] { gateway };
newGateway["GatewayCostMetric"] = new[] { 1 };
managementObject.InvokeMethod("SetGateways", newGateway, null);
}
}
}
}
}
}
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nic">NIC address</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetNameservers(string nic, string dnsServers)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
{
using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
{
newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
}
}
I like the WMILinq solution. While not exactly the solution to your problem, find below a taste of it :
using (WmiContext context = new WmiContext(#"\\.")) {
context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;
context.Log = Console.Out;
var dnss = from nic in context.Source<Win32_NetworkAdapterConfiguration>()
where nic.IPEnabled
select nic;
var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder)
select IPAddress.Parse(s);
}
http://www.codeplex.com/linq2wmi
A far more clear solution is to use the command netsh to change the IP (or setting it back to DHCP)
netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0
Where "Local Area Connection" is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named "Ethernet".
Here are two methods to set the IP and also to set the IP back to DHCP "Obtain an IP address automatically"
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;
}
public bool SetDHCP(string networkInterfaceName)
{
var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
var ipProperties = networkInterface.GetIPProperties();
var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;
if (isDHCPenabled)
return true; // no change necessary
var process = new Process
{
StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" dhcp") { Verb = "runas" }
};
process.Start();
var successful = process.ExitCode == 0;
process.Dispose();
return successful;
}
A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.
using System;
using System.Management;
namespace Utils
{
class NetworkManagement
{
/// <summary>
/// Returns a list of all the network interface class names that are currently enabled in the system
/// </summary>
/// <returns>list of nic names</returns>
public static string[] GetAllNicDescriptions()
{
List<string> nics = new List<string>();
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"])
.Select(x=> new NetworkAdapterConfiguration(x)))
{
nics.Add(config.Description);
}
}
}
return nics.ToArray();
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
{
using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
{
foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
// NAC class was generated by opening a developer console and entering:
// mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
// See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/
using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
{
if (config.SetDNSServerSearchOrder(dnsServers) == 0)
{
RestartNetworkAdapter(nicDescription);
}
}
}
}
}
return false;
}
/// <summary>
/// Restarts a given Network adapter
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
public static void RestartNetworkAdapter(string nicDescription)
{
using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
{
using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
{
foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
{
// NA class was generated by opening dev console and entering
// mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
{
adapter.Disable();
adapter.Enable();
Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
return;
}
}
}
}
}
/// <summary>
/// Get's the DNS Server of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
public static string[] GetNameservers(string nicDescription)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
.Select( x => new NetworkAdapterConfiguration(x)))
{
return config.DNSServerSearchOrder;
}
}
}
return null;
}
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="nicDescription">The full description of the network interface class</param>
/// <param name="ipAddresses">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var config in networkConfigs.Cast<ManagementObject>()
.Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
.Select( x=> new NetworkAdapterConfiguration(x)))
{
// Set the new IP and subnet masks if needed
config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
config.SetGateways(new[] {gateway}, new ushort[] {1});
}
}
}
}
}
}
}
Full source:
https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs
The existing answers have quite broken code. The DNS method does not work at all. Here is code that I used to configure my NIC:
public static class NetworkConfigurator
{
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="ipAddress">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <param name="nicDescription"></param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
{
// Set new IP address and subnet if needed
if (ipAddresses != null || !String.IsNullOrEmpty(subnetMask))
{
if (ipAddresses != null)
{
newIP["IPAddress"] = ipAddresses;
}
if (!String.IsNullOrEmpty(subnetMask))
{
newIP["SubnetMask"] = Array.ConvertAll(ipAddresses, _ => subnetMask);
}
managementObject.InvokeMethod("EnableStatic", newIP, null);
}
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
{
newGateway["DefaultIPGateway"] = new[] { gateway };
newGateway["GatewayCostMetric"] = new[] { 1 };
managementObject.InvokeMethod("SetGateways", newGateway, null);
}
}
}
}
}
}
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nic">NIC address</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public static void SetNameservers(string nicDescription, string[] dnsServers)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
{
using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
{
newDNS["DNSServerSearchOrder"] = dnsServers;
managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
}
}
This maybe more clear:
static NetworkInterface GetNetworkInterface(string macAddress)
{
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (macAddress == ni.GetPhysicalAddress().ToString())
return ni;
}
return null;
}
static ManagementObject GetNetworkInterfaceManagementObject(string macAddress)
{
NetworkInterface ni = GetNetworkInterface(macAddress);
if (ni == null)
return null;
ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = managementClass.GetInstances();
foreach(ManagementObject mo in moc)
{
if (mo["settingID"].ToString() == ni.Id)
return mo;
}
return null;
}
static bool SetupNIC(string macAddress, string ip, string subnet, string gateway, string dns)
{
try
{
ManagementObject mo = GetNetworkInterfaceManagementObject(macAddress);
//Set IP
ManagementBaseObject mboIP = mo.GetMethodParameters("EnableStatic");
mboIP["IPAddress"] = new string[] { ip };
mboIP["SubnetMask"] = new string[] { subnet };
mo.InvokeMethod("EnableStatic", mboIP, null);
//Set Gateway
ManagementBaseObject mboGateway = mo.GetMethodParameters("SetGateways");
mboGateway["DefaultIPGateway"] = new string[] { gateway };
mboGateway["GatewayCostMetric"] = new int[] { 1 };
mo.InvokeMethod("SetGateways", mboGateway, null);
//Set DNS
ManagementBaseObject mboDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
mboDNS["DNSServerSearchOrder"] = new string[] { dns };
mo.InvokeMethod("SetDNSServerSearchOrder", mboDNS, null);
return true;
}
catch (Exception e)
{
return false;
}
}

Categories

Resources