C# DHCP will not change for interfaces that are disconnected - c#

I'm having an issue where my code is setting Static IP and DHCP perfectly fine when I'm connected to the WiFi. However, the Ethernet "local networkinterface" is unchangable, when no cable is connected. The issue is vice-versa for when connected with cable, and trying to set the WiFi interface.
The issue seem to only be present when the interface is disconnected and have no live connection. Anyone else able to reproduce? innput nicName is the name of interface I'm sending from my Form, and is basically used for matching it to the interfaceI want to change
Set StaticIP:
public static bool SetStaticIp(
string nicName,
Object objSite )
{
Site site = (Site)objSite;
//string nicName = adapter.Description;
string ipAddress = $"{site.IP}";
string subnetMask = $"{site.SubnetMask}";
string gateway = $"{site.Gateway}";
string dns1 = $"{site.Dns1}";
string dns2 = $"{site.Dns2}";
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)
{
bool moIpEnable = (bool)mo["IPEnabled"];
string moDesc = (string)mo["Description"];
if (moDesc.Equals(nicName) == 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 (Exception err)
{
Log(LOG_FN.ERROR, $"SetStaticIp({nicDesc}): Klarte ikke sette statisk IP. {err.Message}");
return false;
}
}
}
return true;
}
Set DHCP
public static int SetDHCP(string nicName)
{
//string nicName = sroGlobal.SelectedAdapters.Description;
//string nicName = Name;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
ManagementObjectCollection networkCollection = mc.GetInstances();
string nicDesc = nicName;
if (networkInterface != null)
{
nicDesc = networkInterface.Description;
}
foreach (ManagementObject mo in networkCollection)
{
bool moIpEnable = (bool)mo["IPEnabled"];
string moDesc = (string)mo["Description"];
if (string.Compare(moDesc, nicName,StringComparison.InvariantCultureIgnoreCase) == 0)
{
try
{
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
return 1;
}
catch (Exception err)
{
Log(LOG_FN.ERROR, $"SetDHCP({nicDesc}): Could'nt set DHCP. {err.Message}");
return -1;
}
}
}
return 0;
}
edit 1: format error

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

Object not resolving while using WMI for HyperV

I am using the official example from Microsoft docs to use WMI to start and shut down the virtual machine but Utility and ReturnCode objects aren't getting resolved. When I build the application I get
CS0103 The name 'Utility' does not exist in the current context
I am clueless
ManagementObject vm = Utility.GetTargetComputer(vmName, scope);
&
if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
https://learn.microsoft.com/en-us/windows/win32/hyperv_v2/requeststatechange-msvm-computersystem
Running everything on Server 2019 with Hyper-V running proper.
Here is the complete code:
using System;
using System.Management;
namespace HyperVSamples
{
public class RequestStateChangeClass
{
public static void RequestStateChange(string vmName, string action)
{
ManagementScope scope = new ManagementScope(#"\\.\root\virtualization\v2", null);
ManagementObject vm = Utility.GetTargetComputer(vmName, scope);
if (null == vm)
{
throw new ArgumentException(
string.Format(
"The virtual machine '{0}' could not be found.",
vmName));
}
ManagementBaseObject inParams = vm.GetMethodParameters("RequestStateChange");
const int Enabled = 2;
const int Disabled = 3;
if (action.ToLower() == "start")
{
inParams["RequestedState"] = Enabled;
}
else if (action.ToLower() == "stop")
{
inParams["RequestedState"] = Disabled;
}
else
{
throw new Exception("Wrong action is specified");
}
ManagementBaseObject outParams = vm.InvokeMethod(
"RequestStateChange",
inParams,
null);
if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
{
if (Utility.JobCompleted(outParams, scope))
{
Console.WriteLine(
"{0} state was changed successfully.",
vmName);
}
else
{
Console.WriteLine("Failed to change virtual system state");
}
}
else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
{
Console.WriteLine(
"{0} state was changed successfully.",
vmName);
}
else
{
Console.WriteLine(
"Change virtual system state failed with error {0}",
outParams["ReturnValue"]);
}
}
public static void Main(string[] args)
{
if (args != null && args.Length != 2)
{
Console.WriteLine("Usage: <application> vmName action");
Console.WriteLine("action: start|stop");
return;
}
RequestStateChange(args[0], args[1]);
}
}
}
You have to use a Query instead now:
ManagementScope scope = new ManagementScope(#"root\virtualization\v2");
ObjectQuery query = new ObjectQuery(#"SELECT * FROM Msvm_ComputerSystem WHERE ElementName = '" + vmName + "'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = searcher.Get();
ManagementObject vm = null;
foreach (ManagementObject obj in collection)
{
vm = obj;
break;
}
For the ReturnCode use your own constant instead. You can look them up here: https://learn.microsoft.com/en-us/previous-versions/windows/desktop/virtual/requeststatechange-msvm-computersystem
Something like this:
if ((UInt32)outParams["ReturnValue"] == 0)
{
...
}
0 == all good. Use UInt32 not UInt16!
Remember to run your app as administrator!

Start/Stop BizTalk Send port in C# with WMI

Is it possible to start/stop the send the port using MSBTS_SendPort class through C#?
I have got the port details and the status using Windows WMI and trying to Start/Stop the port
public bool CheckSendPorts()
{
bool returnValue = true;
UserName = "";
Password = "";
ServerName = "testserver";
using (ManagementObjectSearcher searcher = GetWmiSearcher(UserName,Password,ServerName, WMI_SCOPE, $"SELECT * FROM MSBTS_SendPort where Name = 'testSendPort'"))
{
if (searcher == null)
{
//WriteOutput($"No Send Ports found.", true);
return false;
}
foreach (ManagementObject instanceObject in searcher.Get())
{
string portName = instanceObject["Name"] as string;
uint portState = (uint)instanceObject["Status"];
string portStatus = GetPortStatus((uint)instanceObject["Status"]);
bool ignoreLocation = false;
}
}
return returnValue;
}
internal ManagementObjectSearcher GetWmiSearcher(string username,string password,string servername, string wmiScope, string wmiQuery)
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;
if (!string.IsNullOrEmpty(username))
{
connectionOptions.Username = username;
connectionOptions.Password = password;
}
else
{
connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
}
ManagementScope scope = new ManagementScope($#"\\{servername}{wmiScope}");
scope.Options = connectionOptions;
EnumerationOptions enumOptions = new EnumerationOptions();
enumOptions.ReturnImmediately = false;
SelectQuery query = new SelectQuery(wmiQuery);
return new ManagementObjectSearcher(scope, query, enumOptions);
}
private string GetPortStatus(uint code)
{
switch (code)
{
case 1:
return "Bound";
case 2:
return "Stopped";
case 3:
return "Started";
default:
return "Unknown";
}
}
Microsoft documentation suggest there is an method as MSBTS_SendPort.Stop to stop the port. Is it possible?
You can invoke the "stop" or "start" method in your foreach loop while iterating through the instances.
foreach (ManagementObject instanceObject in searcher.Get())
{
string portName = instanceObject["Name"] as string;
uint portState = (uint)instanceObject["Status"];
string portStatus = GetPortStatus((uint)instanceObject["Status"]);
bool ignoreLocation = false;
//invoke method stop with an empty object array for parameters (because this method doesn't take any parameters.
instanceObject.InvokeMethod("stop", new object[]{ });
}

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...

Best way to programmatically configure network adapters in .NET

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