Comment pouvez-vous modifier les parameters réseau (adresse IP, DNS, WINS, nom d’hôte) avec le code en C #

Je développe un assistant pour une machine qui doit être utilisée comme sauvegarde d’autres machines. Lorsqu’il remplace une machine existante, il doit définir son adresse IP, son nom DNS, son nom WINS et son nom d’hôte pour correspondre à la machine remplacée.

Existe-t-il une bibliothèque dans .net (C #) qui me permet de le faire par programmation?

Il existe plusieurs cartes réseau, chacune devant être définie individuellement.

MODIFIER

Merci TimothyP pour ton exemple. Cela m’a fait bouger sur la bonne voie et la réponse rapide a été géniale.

Merci balexandre . Votre code est parfait. J’étais pressé et j’avais déjà adapté l’exemple lié à TimothyP, mais j’aurais aimé avoir votre code plus tôt.

J’ai également développé une routine utilisant des techniques similaires pour changer le nom de l’ordinateur. Je le posterai à l’avenir alors abonnez-vous à ce stream RSS de questions si vous voulez être informé de la mise à jour. Je peux le faire plus tard aujourd’hui ou lundi après un peu de nettoyage.

Je viens de le faire en quelques minutes:

using System; using System.Management; namespace WindowsFormsApplication_CS { class NetworkManagement { public void setIP(ssortingng ip_address, ssortingng subnet_mask) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { ManagementBaseObject setIP; ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic"); newIP["IPAddress"] = new ssortingng[] { ip_address }; newIP["SubnetMask"] = new ssortingng[] { subnet_mask }; setIP = objMO.InvokeMethod("EnableStatic", newIP, null); } } } public void setGateway(ssortingng gateway) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { ManagementBaseObject setGateway; ManagementBaseObject newGateway = objMO.GetMethodParameters("SetGateways"); newGateway["DefaultIPGateway"] = new ssortingng[] { gateway }; newGateway["GatewayCostMesortingc"] = new int[] { 1 }; setGateway = objMO.InvokeMethod("SetGateways", newGateway, null); } } } public void setDNS(ssortingng NIC, ssortingng 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"].ToSsortingng().Contains(NIC)) // and pass in the Description property instead of the name if (objMO["Caption"].Equals(NIC)) { ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder"); newDNS["DNSServerSearchOrder"] = DNS.Split(','); ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); } } } } public void setWINS(ssortingng NIC, ssortingng priWINS, ssortingng secWINS) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { if (objMO["Caption"].Equals(NIC)) { ManagementBaseObject setWINS; ManagementBaseObject wins = objMO.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", priWINS); wins.SetPropertyValue("WINSSecondaryServer", secWINS); setWINS = objMO.InvokeMethod("SetWINSServer", wins, null); } } } } } } 

Refonte du code de balexandre afin que les objects soient éliminés et que les nouvelles fonctionnalités de langage de C # 3.5+ soient utilisées (Linq, var, etc.). Renomme également les variables en noms plus significatifs. J’ai également fusionné certaines fonctions pour pouvoir faire plus de configuration avec moins d’interaction WMI. J’ai supprimé le code WINS car je n’ai plus besoin de configurer WINS. N’hésitez pas à append le code WINS si vous en avez besoin.

Si quelqu’un aime utiliser le code remanié / modernisé, je le remets dans la communauté ici.

 ///  /// Helper class to set networking configuration like IP address, DNS servers, etc. ///  public class NetworkConfigurator { ///  /// Set's a new IP Address and it's Submask of the local machine ///  /// The IP Address /// The Submask IP Address /// The gateway. /// Requires a reference to the System.Management namespace public void SetIP(ssortingng ipAddress, ssortingng subnetMask, ssortingng gateway) { using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var managementObject in networkConfigs.Cast().Where(managementObject => (bool)managementObject["IPEnabled"])) { using (var newIP = managementObject.GetMethodParameters("EnableStatic")) { // Set new IP address and subnet if needed if ((!Ssortingng.IsNullOrEmpty(ipAddress)) || (!Ssortingng.IsNullOrEmpty(subnetMask))) { if (!Ssortingng.IsNullOrEmpty(ipAddress)) { newIP["IPAddress"] = new[] { ipAddress }; } if (!Ssortingng.IsNullOrEmpty(subnetMask)) { newIP["SubnetMask"] = new[] { subnetMask }; } managementObject.InvokeMethod("EnableStatic", newIP, null); } // Set mew gateway if needed if (!Ssortingng.IsNullOrEmpty(gateway)) { using (var newGateway = managementObject.GetMethodParameters("SetGateways")) { newGateway["DefaultIPGateway"] = new[] { gateway }; newGateway["GatewayCostMesortingc"] = new[] { 1 }; managementObject.InvokeMethod("SetGateways", newGateway, null); } } } } } } } ///  /// Set's the DNS Server of the local machine ///  /// NIC address /// Comma seperated list of DNS server addresses /// Requires a reference to the System.Management namespace public void SetNameservers(ssortingng nic, ssortingng dnsServers) { using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var managementObject in networkConfigs.Cast().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic))) { using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder")) { newDNS["DNSServerSearchOrder"] = dnsServers.Split(','); managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); } } } } } } 

J’espère que cela ne vous dérange pas que je vous envoie un exemple, mais c’est vraiment un exemple parfait: http://www.codeproject.com/KB/cs/oazswitchnetconfig.aspx

J’aime la solution WMILinq. Bien que ce ne soit pas exactement la solution à votre problème, trouvez ci-dessous un aperçu:

 using (WmiContext context = new WmiContext(@"\\.")) { context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate; context.Log = Console.Out; var dnss = from nic in context.Source() where nic.IPEnabled select nic; var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder) select IPAddress.Parse(s); } 

http://www.codeplex.com/linq2wmi

Le changement dynamic d’IP en C # est très facile …

S’il vous plaît regardez le code ci-dessous et visitez: http://microsoftdotnetsolutions.blogspot.in/2012/12/dynamic-ip-change-in-c.html

Les réponses existantes ont un code assez cassé. La méthode DNS ne fonctionne pas du tout. Voici le code que j’ai utilisé pour configurer ma carte réseau:

 public static class NetworkConfigurator { ///  /// Set's a new IP Address and it's Submask of the local machine ///  /// The IP Address /// The Submask IP Address /// The gateway. ///  /// Requires a reference to the System.Management namespace public static void SetIP(ssortingng nicDescription, ssortingng[] ipAddresses, ssortingng subnetMask, ssortingng gateway) { using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var managementObject in networkConfigs.Cast().Where(mo => (bool)mo["IPEnabled"] && (ssortingng)mo["Description"] == nicDescription)) { using (var newIP = managementObject.GetMethodParameters("EnableStatic")) { // Set new IP address and subnet if needed if (ipAddresses != null || !Ssortingng.IsNullOrEmpty(subnetMask)) { if (ipAddresses != null) { newIP["IPAddress"] = ipAddresses; } if (!Ssortingng.IsNullOrEmpty(subnetMask)) { newIP["SubnetMask"] = Array.ConvertAll(ipAddresses, _ => subnetMask); } managementObject.InvokeMethod("EnableStatic", newIP, null); } // Set mew gateway if needed if (!Ssortingng.IsNullOrEmpty(gateway)) { using (var newGateway = managementObject.GetMethodParameters("SetGateways")) { newGateway["DefaultIPGateway"] = new[] { gateway }; newGateway["GatewayCostMesortingc"] = new[] { 1 }; managementObject.InvokeMethod("SetGateways", newGateway, null); } } } } } } } ///  /// Set's the DNS Server of the local machine ///  /// NIC address /// Comma seperated list of DNS server addresses /// Requires a reference to the System.Management namespace public static void SetNameservers(ssortingng nicDescription, ssortingng[] dnsServers) { using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var managementObject in networkConfigs.Cast().Where(mo => (bool)mo["IPEnabled"] && (ssortingng)mo["Description"] == nicDescription)) { using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder")) { newDNS["DNSServerSearchOrder"] = dnsServers; managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); } } } } } } 

Un exemple légèrement plus concis qui s’appuie sur les autres réponses. J’ai tiré parti de la génération de code fournie avec Visual Studio pour supprimer la plupart des codes d’appel supplémentaires et les remplacer par des objects typés.

  using System; using System.Management; namespace Utils { class NetworkManagement { ///  /// Returns a list of all the network interface class names that are currently enabled in the system ///  /// list of nic names public static ssortingng[] GetAllNicDescriptions() { List nics = new List(); using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var config in networkConfigs.Cast() .Where(mo => (bool)mo["IPEnabled"]) .Select(x=> new NetworkAdapterConfiguration(x))) { nics.Add(config.Description); } } } return nics.ToArray(); } ///  /// Set's the DNS Server of the local machine ///  /// The full description of the network interface class /// Comma seperated list of DNS server addresses /// Requires a reference to the System.Management namespace public static bool SetNameservers(ssortingng nicDescription, ssortingng[] dnsServers, bool restart = false) { using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances()) { foreach (ManagementObject mboDNS in networkConfigs.Cast().Where(mo => (bool)mo["IPEnabled"] && (ssortingng)mo["Description"] == nicDescription)) { // NAC class was generated by opening a developer console and entering: // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/ using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS)) { if (config.SetDNSServerSearchOrder(dnsServers) == 0) { RestartNetworkAdapter(nicDescription); } } } } } return false; } ///  /// Restarts a given Network adapter ///  /// The full description of the network interface class public static void RestartNetworkAdapter(ssortingng nicDescription) { using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter")) { using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances()) { foreach (ManagementObject mboDNS in networkConfigs.Cast().Where(mo=> (ssortingng)mo["Description"] == nicDescription)) { // NA class was generated by opening dev console and entering // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs using (NetworkAdapter adapter = new NetworkAdapter(mboDNS)) { adapter.Disable(); adapter.Enable(); Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect return; } } } } } ///  /// Get's the DNS Server of the local machine ///  /// The full description of the network interface class public static ssortingng[] GetNameservers(ssortingng nicDescription) { using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var config in networkConfigs.Cast() .Where(mo => (bool)mo["IPEnabled"] && (ssortingng)mo["Description"] == nicDescription) .Select( x => new NetworkAdapterConfiguration(x))) { return config.DNSServerSearchOrder; } } } return null; } ///  /// Set's a new IP Address and it's Submask of the local machine ///  /// The full description of the network interface class /// The IP Address /// The Submask IP Address /// The gateway. /// Requires a reference to the System.Management namespace public static void SetIP(ssortingng nicDescription, ssortingng[] ipAddresses, ssortingng subnetMask, ssortingng gateway) { using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (var networkConfigs = networkConfigMng.GetInstances()) { foreach (var config in networkConfigs.Cast() .Where(mo => (bool)mo["IPEnabled"] && (ssortingng)mo["Description"] == nicDescription) .Select( x=> new NetworkAdapterConfiguration(x))) { // Set the new IP and subnet masks if needed config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask)); // Set mew gateway if needed if (!Ssortingng.IsNullOrEmpty(gateway)) { config.SetGateways(new[] {gateway}, new ushort[] {1}); } } } } } } } 

Source complète: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs