I am writing an application to make changes to network adapter IP address settings. Only the basic IP settings is what I will change from the application.
Is there any way for me to make use of some sort of "link" or "path" to open the "Advanced TCP/IP Settings" screen normally accessed VIA the "Advanced" button in the TCP/IPv4 Properties screen?
The above screen capture shows the highlighted button that would normally be used to open the advanced TCP/IP Settings screen. I need a way to open this exact screen from my application directly using a button.
You could do something like:
System.Diagnostics.Process.Start("ncpa.cpl"); // opens network connections window
Thread.Sleep(500); // give time for window to open
SendKeys.Send("(^a){RIGHT}(%f)r"); // select all (ctrl+a), right arrow, alt+f, r
You can set the IP address of a network adapter by using the following code
public void setIP(string IPAddress,string SubnetMask, string Gateway)
{
ManagementClass objMC = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach(ManagementObject objMO in objMOC)
{
if (!(bool) objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] {Gateway};
objNewGate["GatewayCostMetric"] = new int[] {1};
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] {IPAddress};
objNewIP["SubnetMask"] = new string[] {SubnetMask};
objSetIP = objMO.InvokeMethod("EnableStatic",objNewIP,null);
objSetIP = objMO.InvokeMethod("SetGateways",objNewGate,null);
Console.WriteLine(
"Updated IPAddress, SubnetMask and Default Gateway!");
}
catch(Exception ex)
{
MessageBox.Show("Unable to Set IP : " + ex.Message); }
}
Related
I have a code that tries to access the services of another computer.
try
{
var serviceName = "MyService";
var ip = "10.10.11.16";
var username = "SomeUser";
var password = "APassword";
var connectoptions = new ConnectionOptions();
connectoptions.Impersonation = ImpersonationLevel.Impersonate;
connectoptions.Authentication = AuthenticationLevel.Packet;
connectoptions.EnablePrivileges = true;
connectoptions.Username = username;
connectoptions.Password = password;
var scope = new ManagementScope("\\\\10.10.11.16\\root\\cimv2");
scope.Options = connectoptions;
var query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
var collection = searcher.Get();
foreach (ManagementObject service in collection.OfType<ManagementObject>())
{
if (service["started"].Equals(true))
{
service.InvokeMethod("StopService", null);
BtnStartStop.Content = "Stop";
LblService.Content = serviceName;
LblServiceStatus.Content = "Stopped";
}
else
{
service.InvokeMethod("StartService", null);
BtnStartStop.Content = "Stop";
LblService.Content = serviceName;
LblServiceStatus.Content = "Running";
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Will this work on Server and client only? Won't this work on regular pc to another regular pc? Each time I run this when I get to the part of:
var collection = searcher.Get();
I get an error of
Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))
Do you have an idea on to make this work? Thank you.
STEPS DONE SO FAR
Followed the instruction on
https://learn.microsoft.com/en-us/windows/win32/wmisdk/connecting-to-wmi-remotely-starting-with-vista
typed in the cmd with admin privilege
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
I even turned off the firewall just to be sure.
edited the registry of the pc I am connecting to this:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\AllowAnonymousCallback
Data type
REG\_DWORD
As for the antivirus, the pc I am connecting to does not have any anti virus.
I still get the same error.
As #colosso pointed out, you are receiving that error message because you do not have permission on the remote host to connect to the WMI service.
You should follow the instructions here to ensure the remote host is configured to allow your connection.
First Process:
Get the column ip_address,subnet from database
I will set the column ip address to label1.text and subnet to label2.text
string connection = "Server=192.168.1.10;Database=xxxxx;User Id=xxxxx;Password=xxxxxx;";
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
var query = "SELECT TOP 1 ip_address,subnet,gateway FROM computer_info WHERE pc_name = HOST_NAME() ORDER BY id DESC";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// column ip
string ip_address = dr["ip_address"].ToString();
string sub_net = dr["subnet"].ToString();
string gateway = dr["gateway"].ToString();
label1.Text = ip_address;
label2.Text = sub_net;
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Second Process:
I want to change my ip address and my subnet
Note: the value of ip address and subnet is from database
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"])
{
try
{
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);
}
catch (Exception)
{
throw;
}
}
}
}
Third process execute
Note: I have 2 example code here 1 is working and 2 not working
private void button1_Click_1(object sender, EventArgs e)
{
setIP(
// if i use this static string value my address is changing.
"192.168.1.5",
"255.255.255.0"
);
///---------------------------------------///////////////////////////////////////
setIP(
//the value inside of label1 , label2 is from database. ??? the question is why there is no result if the value came from the database.
label1.Text,
label2.Text
);
}
I hope you will help me guys.. thanks.
I would make sure my connection string is working. This the only thing I can see. Check while stepping through your code to see if you get a value back. Also make sure your router and modem have port forwarding on if you are trying to reach a database on your domain. However, if your trying to reach a server outside the network then I would definitely make sure you can reach the server by ping the server.
Easiest way to debug is to set BreakPoint at setIP function and view the value of label2.Text in "Immediate Window" [To open Immediate Window in VS menu : Debug -> Window -> Immediate Window]. Please confirm whether you are getting value here. If you are not getting value here, share your front-end label tag you have used.
I want to change NETWORK CONFIGURATION programmatically. Everything is working fine, only IP of DNS doesn't want to change, it stays empty.
I use next code to change configuration:
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))
if (objMO["Caption"].ToString().Contains(NIC))
{
try
{
ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split('.');
ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
catch (Exception)
{
throw;
}
}
}
}
}
If you only have one DNS IP address, you need assign the value as
newDNS["DNSServerSearchOrder"] = new string[]{DNS};
If you have two DNS IP addesses and they are separated by ';', you need assign the value as
newDNS["DNSServerSearchOrder"] = DNS.Split(';');
The input value must be a string array.
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.
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.