Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to programmatically configure network adapters in .NET

Tags:

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?

like image 448
TimK Avatar asked Mar 27 '09 10:03

TimK


People also ask

How do I manually configure network adapter?

In Windows 10, click Start > Settings > Control Panel > Network and Internet > Network and Sharing Center > Change adapter settings. In the list of network connections that opens, select the connection you are using to connect to your ISP (wireless or LAN). Double-click on the connection.

How do I assign an IP address to an adapter?

Right-click on the network adapter you want to assign an IP address and click Properties. Highlight Internet Protocol Version 4 (TCP/IPv4) then click the Properties button. Now change the IP, Subnet mask, Default Gateway, and DNS Server Addresses. When you're finished click OK.


2 Answers

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.

like image 104
PaulB Avatar answered Sep 25 '22 13:09

PaulB


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;     } 
like image 42
Kim Ki Won Avatar answered Sep 22 '22 13:09

Kim Ki Won