Set ipv6 for windows with C# - 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.

Related

How to run services of one pc from another pc

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.

Cannot connect Hyper-V VM Network Adapter to a Hyper-V Switch via WMI in C#

I am having quite some difficulty connecting a specific, existing network adapter to an existing switch. I can create a new network adapter and connect it to my VM through several examples posted online but cannot make that extra step. The following function finds my network adapter and executes without error, but does not otherwise make the connection. Any assistance is greatly appreciated!
**EDIT: Solved, see code below.**
Solved:
public static void ConnectInterfaceToSwitch(string VmName, string networkInterfaceName, string switchName)
{
ManagementScope scope = new ManagementScope(#"root\virtualization\v2");
ManagementObject mgtSvc = WmiUtilities.GetVirtualMachineManagementService(scope);
ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope);
ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(VmName, scope);
ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine);
ManagementObjectCollection portsSettings = virtualMachineSettings.GetRelated("Msvm_SyntheticEthernetPortSettingData", "Msvm_VirtualSystemSettingDataComponent", null, null, null, null, false, null);
{
foreach (ManagementObject portSettings in portsSettings)
{
if (portSettings["ElementName"].Equals(networkInterfaceName))
{
Console.WriteLine("Adapter found: " + networkInterfaceName);
ManagementObjectCollection connections = portSettings.GetRelated("Msvm_EthernetPortAllocationSettingData");
foreach (ManagementObject connection in connections)
{
connection["HostResource"] = new string[] { ethernetSwitch.Path.Path };
connection["EnabledState"] = 2; // 2 means "Enabled"
ManagementBaseObject inParams = mgtSvc.GetMethodParameters("ModifyResourceSettings");
inParams["ResourceSettings"] = new string[] { connection.GetText(TextFormat.WmiDtd20) };
ManagementBaseObject outParams = mgtSvc.InvokeMethod("ModifyResourceSettings", inParams, null);
WmiUtilities.ValidateOutput(outParams, scope);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Connected VM '{0}' to switch '{1}'.", VmName, switchName));
}
}
}
}
}

Changing DNS (C#, .NET) is not working

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.

C# Winforms button to specific screen in Windows

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); }
}

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

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

Categories

Resources