setup other computer network and configure the ip address programatically C# - c#

I have some sample codes where I can change my own ip address.
Now i have a problem regarding changing the ip address of my networks.
When i mean networks (Computers that are connected to the lan)
I want to connect and configure their ip address as well.
Example
I have 2 computers and the ip addresses are 192.168.1.6 - Computer 1 and 192.168.1.7 - Computer 2. So now I am at computer 1 and I want to connect to 192.168.1.7 and change the ip address to 192.168.1.8
CODE
private void button1_Click_1(object sender, EventArgs e)
{
//example of ip 10.11.3.120
try
{
setIP();
setGateway();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
setIP();
setGateway();
MessageBox.Show("Update Success");
}
}
private void setIP()
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
try
{
ManagementBaseObject setIP;
ManagementBaseObject newIP =
objMO.GetMethodParameters("EnableStatic");
//string ip_address = "10.11.3.120";
//string subnet_mask = "255.255.255.0";
newIP["IPAddress"] = new string[] { textBox1.Text };
newIP["SubnetMask"] = new string[] { textBox2.Text };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
public void setGateway()
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
try
{
ManagementBaseObject setGateway;
ManagementBaseObject newGateway =
objMO.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { textBox3.Text };
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
}
catch (Exception)
{
throw;
}
}
}
}

This is not a direct answer. However, you should have all the information you need here
Connecting to WMI Remotely with C#
In short you will need create a system ManagementScope
Note System.Management was the original .NET namespace used to access
WMI; however, the APIs in this namespace generally are slower and do
not scale as well relative to their more modern
Microsoft.Management.Infrastructure counterparts.
However
Create a ManagementScope object, using the name of the computer and the WMI path, and connect to your target with a call to ManagementScope.Connect().
If you connect to a remote computer in a different domain or using a different user name and password, then you must use a ConnectionOptions object in the call to the ManagementScope.
The ConnectionOptions contains properties for describing the
Authentication, Impersonation, username, password, and other
connection options.
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
// options takes more arguments, you need to read up on what you want
ManagementScope scope = new ManagementScope("\\\\FullComputerName\\root\\cimv2", options);
scope.Connect();
ManagementPath path = new ManagementPath("Win32_NetworkAdapterConfiguration");
ObjectGetOptions o = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
ManagementClass objMC = new ManagementClass(scope, path, o);
...
Generally speaking, it is recommended that you set your Impersonation
level to Impersonate unless explicitly needed otherwise
Additional reading
Connecting to WMI Remotely with C#
ManagementScope Class
ConnectionOptions Class
ObjectGetOptions Class
ManagementPath Class
ManagementClass Class
Disclaimer : You will have to read about these topics and work out what you need in your situation.

Related

some problems about modify IP address with System.Management(WMI)

I want to know the meaning of "ManagementObject" returnValue, such as '2147947410'.
Does C# have any other options to modify IP address, except through WMI?
How to prevent windows change IP address to 169.254.XXX, when it detect IP conflict?
Before run the code, I modify one network's IP address to 192.168.1.66(not my targe network). [Fig.1]
Then run the code , it would not throw any exceptions, outPar["returnValue"] returns value 2147947410, but if I open target network's opions, the IP address is blank! [Fig.2]
And, if type "ipconfig" in CMD, I will see the target network's IP is 169.254.XXX. I know that means "ip conflict". [Fig.2]
Below is the code.
static void Main(string[] args)
{
// Run Code in Admin mode.
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["IPEnabled"])
continue;
string[] addresses = (string[])mo["IPAddress"];
Console.WriteLine("开始修改");
try
{
//设置ip地址和子网掩码 
inPar = mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = new string[] { "192.168.1.66" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod("EnableStatic", inPar, null);
Console.WriteLine(outPar["returnValue"]);
//设置网关地址 
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { "0.0.0.0" };
outPar = mo.InvokeMethod("SetGateways", inPar, null);
}
catch (Exception e)
{
throw e;
}
//设置DNS 
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[] { "0.0.0.0" };
outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
break;
}
Console.ReadLine();
}

How to Change DNS with C# on Windows 10

I'm trying to change the DNS on Windows 10 through VB.NET.
I have code that works on Windows 7, however it does not work on Windows 10.
Here is my code for Windows 7 that changes the DNS:
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
ManagementBaseObject objdns = mo.GetMethodParameters("SetDNSServerSearchOrder");
if (objdns != null)
{
string[] s = { "192.168.XX.X", "XXX.XX.X.XX" };
objdns["DNSServerSearchOrder"] = s;
mo.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
My question is, how do I get this to work on Windows 10 OS?
First you need to get the NetworkInterface you want to set/unset DNS
I've tested this code on the latest version of Windows 10 and it works like a charm!
Here is the code to find the active Ethernet or Wifi network (Not 100% accurate but useful in most cases)
public static NetworkInterface GetActiveEthernetOrWifiNetworkInterface()
{
var Nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
a => a.OperationalStatus == OperationalStatus.Up &&
(a.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || a.NetworkInterfaceType == NetworkInterfaceType.Ethernet) &&
a.GetIPProperties().GatewayAddresses.Any(g => g.Address.AddressFamily.ToString() == "InterNetwork"));
return Nic;
}
SetDNS
public static void SetDNS(string DnsString)
{
string[] Dns = { DnsString };
var CurrentInterface = GetActiveEthernetOrWifiNetworkInterface();
if (CurrentInterface == null) return;
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
if (objMO["Description"].ToString().Equals(CurrentInterface.Description))
{
ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder");
if (objdns != null)
{
objdns["DNSServerSearchOrder"] = Dns;
objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
}
}
}
}
}
UnsetDNS
public static void UnsetDNS()
{
var CurrentInterface = GetActiveEthernetOrWifiNetworkInterface();
if (CurrentInterface == null) return;
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
if (objMO["Description"].ToString().Equals(CurrentInterface.Description))
{
ManagementBaseObject objdns = objMO.GetMethodParameters("SetDNSServerSearchOrder");
if (objdns != null)
{
objdns["DNSServerSearchOrder"] = null;
objMO.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
}
}
}
}
}
Usage
SetDNS("127.0.0.1");
Combining multiple solutions I found that the following code is working great for Windows 10 and 8.1 (others not tested, but should work as well):
public static void setDNS(string NIC, string DNS)
{
ConnectionOptions options = PrepareOptions();
ManagementScope scope = PrepareScope(Environment.MachineName, options, #"\root\CIMV2");
ManagementPath managementPath = new ManagementPath("Win32_NetworkAdapterConfiguration");
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementClass mc = new ManagementClass(scope, managementPath, objectGetOptions);
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
if (mo["Caption"].ToString().Contains(NIC))
{
try
{
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split(',');
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadKey();
throw;
}
}
}
}
}
The application needs to run with elevated permissions (in my case I'm starting an elevated process running an .exe):
private void callSwapDNS(string NIC, string DNS)
{
const int ERROR_CANCELLED = 1223; //The operation was canceled by the user.
ProcessStartInfo info = new ProcessStartInfo(#"swap.exe");
string wrapped = string.Format(#"""{0}"" ""{1}""", NIC, DNS);
info.Arguments = wrapped;
info.UseShellExecute = true;
info.Verb = "runas";
info.WindowStyle = ProcessWindowStyle.Hidden;
try
{
Process.Start(info);
Thread.Sleep(500);
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode == ERROR_CANCELLED)
MessageBox.Show("Why you no select Yes?");
else
throw;
}
}
Using mo["Caption"].ToString().Contains(NIC) doesn't work for Windows 10 as the WMI query returns the NIC-Name leading with [000000]
[000000] Intel(R) 82574L Gigabit Network Connection
on my Windows 10 machine.
Credit to the following answers: [WMI not working after upgrading to Windows 10
WMI not working after upgrading to Windows 10
How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#
and the answers to this question.
With Windows 10 you may need authentication first. Pass a ConnectionOptions instance to a ManagementScope constructor, defining your Authentication and Impersonation properties.
Try this:
// Method to prepare the WMI query connection options.
public static ConnectionOptions PrepareOptions ( )
{
ConnectionOptions options = new ConnectionOptions ( );
options . Impersonation = ImpersonationLevel . Impersonate;
options . Authentication = AuthenticationLevel . Default;
options . EnablePrivileges = true;
return options;
}
// Method to prepare WMI query management scope.
public static ManagementScope PrepareScope ( string machineName , ConnectionOptions options , string path )
{
ManagementScope scope = new ManagementScope ( );
scope . Path = new ManagementPath ( #"\\" + machineName + path );
scope . Options = options;
scope . Connect ( );
return scope;
}
// Set DNS.
ConnectionOptions options = PrepareOptions ( );
ManagementScope scope = PrepareScope ( Environment . MachineName , options , #"\root\CIMV2" );
ManagementClass mc = new ManagementClass(scope, "Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
ManagementBaseObject objdns = mo.GetMethodParameters("SetDNSServerSearchOrder");
if (objdns != null)
{
string[] s = { "192.168.XX.X", "XXX.XX.X.XX" };
objdns["DNSServerSearchOrder"] = s;
mo.InvokeMethod("SetDNSServerSearchOrder", objdns, null);
Based on this answer:
WMI not working after upgrading to Windows 10
This is the code I use to do this and it works:
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="NIC">NIC address</param>
/// <param name="DNS">DNS server address</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
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))
{
try
{
ManagementBaseObject newDNS =
objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split(',');
ManagementBaseObject setDNS =
objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch (Exception)
{
throw;
}
}
}
}
}
Hope it helps...

stop process using WMI

I'm trying to stop a process on a remote machine using WMI
try
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = IFS_username;
connectionOptions.Password = IFS_password;
connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope("\\\\" + IFS_IP + "\\root\\CIMV2", connectionOptions);
scope.Connect();
ManagementPath path = new ManagementPath("Win32_Process");
ManagementClass services;
services = new ManagementClass(scope, path, null);
foreach (ManagementObject service in services.GetInstances())
{
if (service.GetPropertyValue("Name").ToString().ToLower()=="notepad.exe")
{
service.InvokeMethod("Terminate", null);
}
}
}
catch (Exception ex)
{ textBox1.Text = ex.ToString(); }
}
But I got the following exception
System.Runtime.InteropServices.COMException (0x800706BA):
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
at System.Management.ThreadDispatch.Start()
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementScope.Connect()
After some messing around the exception changed to
enter code here
I have checked couple of pages and it seems my method is correct, but I'm not able to find a solution for the exception.

Configure Win 7 Network Adapter Programatically in C#

I want to configure all active network adapters in windows 7 programatically through c#.
I have tried following code:
string newIPAddress = "100.200.100.11";
string newSubnetMask = "255.255.255.1";
string[] newGateway = { "100.200.100.1" };
ManagementObjectSearcher m = new ManagementObjectSearcher();
m.Query = new ObjectQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True");
foreach (ManagementObject mo in m.Get())
{
try
{
ManagementBaseObject setIP;
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { newIPAddress };
newIP["SubnetMask"] = new string[] { newSubnetMask };
setIP = mo.InvokeMethod("EnableStatic", newIP, null);
mo.InvokeMethod("SetGateways", new object[] { newGateway, new string[] { "1" } });
mo.InvokeMethod("SetDNSServerSearchOrder", new object[] { new string[] { "100.100.100.100" } });
}
catch (Exception)
{
throw;
}
}
But it just updates the default gateways and changes nothing else.
I have used netsh command as well:
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
Console.WriteLine(adapter.Name);
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"" + adapter.Name + "\" static 192.168.0.10 255.255.255.0 192.168.0.1 ");
psi.UseShellExecute = false;
p.StartInfo = psi;
p.Start();
}
But it works for first adapter and after that it thows an error:
"Failed to configure the DHCP service. The interface may be disconnected."
How can i configure all adapters in c#?
I know this post is old but I believe you are having this issue because you are trying to set the IP of multiple adaptors to the Exact same IP.

Get hardware information of Windows Server

Currently I'm using following methods to get hardware information (network adapter, processor, hdd)
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_processor");
ManagementObject dsk = new ManagementObject(#"win32_logicaldisk.deviceid=""c:""");
My app is desktop, client-server (app and db are installed on server).
This methods get information for client. Is there a way to get hardware information for some node on lan - I want to get hardware information for server?
This is a subroutine I use in order to query remote hosts (here I assume I already configured WMI on the remote computer):
public string getWMI(string[] parameters)
{
string ip = parameters[0];
string username = parameters[1];
string password = parameters[2];
string query = parameters[3];
string result = "";
ConnectionOptions options = new ConnectionOptions();
ManagementScope scope;
options.Username = username;
options.Password = password;
try
{
scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", options);
scope.Connect();
if (scope.IsConnected)
{
ObjectQuery q = new ObjectQuery(query);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, q);
ManagementObjectCollection objCol = searcher.Get();
foreach (ManagementObject mgtObject in objCol)
{
result = result + mgtObject.GetText(TextFormat.CimDtd20);
}
}
else
{
}
}
catch (Exception e)
{
writeLogFile("WMI Error: " + e.Message);
writeLog("WMI Error: " + e.Message);
}
return result;
}
In that subroutine I use a direct query such as "select * from Win32_ComputerSystem" but you can use ManagementClass as well.
I want to get hardware information for server?
WMI can poin to another server as long as:
The eserver exposes WMI
The fireawall does not block it.
Your user account has the rights on the other server.
Simple like that.

Categories