2008-10-16 6 views
57

Je développe un assistant pour une machine qui doit être utilisée comme sauvegarde d'autres machines. Lorsqu'il remplace une machine existante, elle doit définir son adresse IP, DNS, WINS et son nom d'hôte pour correspondre à la machine à remplacer.Comment pouvez-vous modifier les paramètres réseau (adresse IP, DNS, WINS, nom d'hôte) avec le code en C#

Y at-il une bibliothèque dans .net (C#) qui me permet de faire cela par programmation?

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

EDIT

Merci pour votre TimothyP exemple. Il m'a fait bouger sur la bonne voie et la réponse rapide était géniale.

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

J'ai également développé une routine en utilisant des techniques similaires pour changer le nom de l'ordinateur. Je l'afficherai à l'avenir donc abonnez-vous à cette question RSS feed si vous voulez être informé de la mise à jour. Je pourrais le faire plus tard aujourd'hui ou lundi après un peu de nettoyage.

Répondre

77

Juste fait cela en quelques minutes:

using System; 
using System.Management; 

namespace WindowsFormsApplication_CS 
{ 
    class NetworkManagement 
    { 
     /// <summary> 
     /// Set's a new IP Address and it's Submask of the local machine 
     /// </summary> 
     /// <param name="ip_address">The IP Address</param> 
     /// <param name="subnet_mask">The Submask IP Address</param> 
     /// <remarks>Requires a reference to the System.Management namespace</remarks> 
     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; 
        } 


       } 
      } 
     } 
     /// <summary> 
     /// Set's a new Gateway address of the local machine 
     /// </summary> 
     /// <param name="gateway">The Gateway IP Address</param> 
     /// <remarks>Requires a reference to the System.Management namespace</remarks> 
     public void setGateway(string gateway) 
     { 
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
      ManagementObjectCollection objMOC = objMC.GetInstances(); 

      foreach (ManagementObject objMO in objMOC) 
      { 
       if ((bool)objMO["IPEnabled"]) 
       { 
        try 
        { 
         ManagementBaseObject setGateway; 
         ManagementBaseObject newGateway = 
          objMO.GetMethodParameters("SetGateways"); 

         newGateway["DefaultIPGateway"] = new string[] { gateway }; 
         newGateway["GatewayCostMetric"] = new int[] { 1 }; 

         setGateway = objMO.InvokeMethod("SetGateways", newGateway, null); 
        } 
        catch (Exception) 
        { 
         throw; 
        } 
       } 
      } 
     } 
     /// <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; 
         } 
        } 
       } 
      } 
     } 
     /// <summary> 
     /// Set's WINS of the local machine 
     /// </summary> 
     /// <param name="NIC">NIC Address</param> 
     /// <param name="priWINS">Primary WINS server address</param> 
     /// <param name="secWINS">Secondary WINS server address</param> 
     /// <remarks>Requires a reference to the System.Management namespace</remarks> 
     public void setWINS(string NIC, string priWINS, string 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)) 
        { 
         try 
         { 
          ManagementBaseObject setWINS; 
          ManagementBaseObject wins = 
          objMO.GetMethodParameters("SetWINSServer"); 
          wins.SetPropertyValue("WINSPrimaryServer", priWINS); 
          wins.SetPropertyValue("WINSSecondaryServer", secWINS); 

          setWINS = objMO.InvokeMethod("SetWINSServer", wins, null); 
         } 
         catch (Exception) 
         { 
          throw; 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+3

Tout comme EnableStatic, existe-t-il un moyen de réinitialiser l'adresse IP en mode dynamique? EnableDynamic? Je veux construire un outil pour basculer entre une adresse IP statique et dynamique en un seul clic. Merci. – aalaap

+6

Pour ceux qui sont intéressés, vous pouvez trouver une liste de toutes les propriétés et méthodes sur ce ManagementObject ici: http://msdn.microsoft.com/en-us/library/aa394217.aspx – Paccc

+1

@balexandre comment pouvons-nous rendre réalisable sous limité compte d'utilisateur? – Eric

5

J'aime la solution WMILinq. Bien que pas exactement la solution à votre problème, trouver ci-dessous un avant-goût de celui-ci:

using (WmiContext context = new WmiContext(@"\\.")) { 

    context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate; 
    context.Log = Console.Out; 

    var dnss = from nic in context.Source<Win32_NetworkAdapterConfiguration>() 
      where nic.IPEnabled 
      select nic; 

    var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder) 
      select IPAddress.Parse(s); 
} 

http://www.codeplex.com/linq2wmi

23

Refonte le code de balexandre un peu pour objets obtient disposés et les nouvelles fonctions linguistiques de 3.5+ C# sont utilisés (Linq, var, etc.) Aussi renommé les variables à des noms plus significatifs. J'ai également fusionné certaines des fonctions pour être en mesure de 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 à ajouter le code WINS si vous en avez besoin. Pour le cas où quelqu'un aime utiliser le code refacturé/modernisé, je le mets dans la communauté ici.

/// <summary> 
/// Helper class to set networking configuration like IP address, DNS servers, etc. 
/// </summary> 
public class NetworkConfigurator 
{ 
    /// <summary> 
    /// Set's a new IP Address and it's Submask of the local machine 
    /// </summary> 
    /// <param name="ipAddress">The IP Address</param> 
    /// <param name="subnetMask">The Submask IP Address</param> 
    /// <param name="gateway">The gateway.</param> 
    /// <remarks>Requires a reference to the System.Management namespace</remarks> 
    public void SetIP(string ipAddress, string subnetMask, string gateway) 
    { 
     using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
     { 
      using (var networkConfigs = networkConfigMng.GetInstances()) 
      { 
       foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"])) 
       { 
        using (var newIP = managementObject.GetMethodParameters("EnableStatic")) 
        { 
         // Set new IP address and subnet if needed 
         if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask))) 
         { 
          if (!String.IsNullOrEmpty(ipAddress)) 
          { 
           newIP["IPAddress"] = new[] { ipAddress }; 
          } 

          if (!String.IsNullOrEmpty(subnetMask)) 
          { 
           newIP["SubnetMask"] = new[] { subnetMask }; 
          } 

          managementObject.InvokeMethod("EnableStatic", newIP, null); 
         } 

         // Set mew gateway if needed 
         if (!String.IsNullOrEmpty(gateway)) 
         { 
          using (var newGateway = managementObject.GetMethodParameters("SetGateways")) 
          { 
           newGateway["DefaultIPGateway"] = new[] { gateway }; 
           newGateway["GatewayCostMetric"] = new[] { 1 }; 
           managementObject.InvokeMethod("SetGateways", newGateway, null); 
          } 
         } 
        } 
       } 
      } 
     } 
    } 

    /// <summary> 
    /// Set's the DNS Server of the local machine 
    /// </summary> 
    /// <param name="nic">NIC address</param> 
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param> 
    /// <remarks>Requires a reference to the System.Management namespace</remarks> 
    public void SetNameservers(string nic, string dnsServers) 
    { 
     using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
     { 
      using (var networkConfigs = networkConfigMng.GetInstances()) 
      { 
       foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic))) 
       { 
        using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder")) 
        { 
         newDNS["DNSServerSearchOrder"] = dnsServers.Split(','); 
         managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); 
        } 
       } 
      } 
     } 
    } 
} 
+0

Quel est le paramètre 'nic' censé contenir dans la fonction setNameservers? – clamp

+0

son nom (description) de l'interface réseau. vous pouvez les énumérer en utilisant NetworkInterface.GetAllNetworkInterfaces(). – Marc

+2

Remarque: vous devez ajouter une référence à System.Management à votre projet. – Jeff

1

changement dynamique IP en C# est très facile ...

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

+0

c'est aussi une bonne solution! –

+0

Bien que ce lien puisse répondre à la question, il est préférable d'inclure les parties essentielles de la réponse ici et fournir le lien pour référence. Les réponses à lien uniquement peuvent devenir invalides si la page liée change. - [De l'examen] (/ review/low-quality-posts/18747472) – dferenc

0

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 mon NIC:

public static class NetworkConfigurator 
{ 
    /// <summary> 
    /// Set's a new IP Address and it's Submask of the local machine 
    /// </summary> 
    /// <param name="ipAddress">The IP Address</param> 
    /// <param name="subnetMask">The Submask IP Address</param> 
    /// <param name="gateway">The gateway.</param> 
    /// <param name="nicDescription"></param> 
    /// <remarks>Requires a reference to the System.Management namespace</remarks> 
    public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway) 
    { 
     using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
     { 
      using (var networkConfigs = networkConfigMng.GetInstances()) 
      { 
       foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)) 
       { 
        using (var newIP = managementObject.GetMethodParameters("EnableStatic")) 
        { 
         // Set new IP address and subnet if needed 
         if (ipAddresses != null || !String.IsNullOrEmpty(subnetMask)) 
         { 
          if (ipAddresses != null) 
          { 
           newIP["IPAddress"] = ipAddresses; 
          } 

          if (!String.IsNullOrEmpty(subnetMask)) 
          { 
           newIP["SubnetMask"] = Array.ConvertAll(ipAddresses, _ => subnetMask); 
          } 

          managementObject.InvokeMethod("EnableStatic", newIP, null); 
         } 

         // Set mew gateway if needed 
         if (!String.IsNullOrEmpty(gateway)) 
         { 
          using (var newGateway = managementObject.GetMethodParameters("SetGateways")) 
          { 
           newGateway["DefaultIPGateway"] = new[] { gateway }; 
           newGateway["GatewayCostMetric"] = new[] { 1 }; 
           managementObject.InvokeMethod("SetGateways", newGateway, null); 
          } 
         } 
        } 
       } 
      } 
     } 
    } 

    /// <summary> 
    /// Set's the DNS Server of the local machine 
    /// </summary> 
    /// <param name="nic">NIC address</param> 
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param> 
    /// <remarks>Requires a reference to the System.Management namespace</remarks> 
    public static void SetNameservers(string nicDescription, string[] dnsServers) 
    { 
     using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
     { 
      using (var networkConfigs = networkConfigMng.GetInstances()) 
      { 
       foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)) 
       { 
        using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder")) 
        { 
         newDNS["DNSServerSearchOrder"] = dnsServers; 
         managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); 
        } 
       } 
      } 
     } 
    } 
} 
0

Un exemple légèrement plus concis qui s'ajoute aux autres réponses ici. J'ai tiré parti de la génération de code fournie avec Visual Studio pour supprimer la plupart du code d'invocation supplémentaire et le remplacer par des objets typés à la place.

using System; 
    using System.Management; 

    namespace Utils 
    { 
     class NetworkManagement 
     { 
      /// <summary> 
      /// Returns a list of all the network interface class names that are currently enabled in the system 
      /// </summary> 
      /// <returns>list of nic names</returns> 
      public static string[] GetAllNicDescriptions() 
      { 
       List<string> nics = new List<string>(); 

       using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
       { 
        using (var networkConfigs = networkConfigMng.GetInstances()) 
        { 
         foreach (var config in networkConfigs.Cast<ManagementObject>() 
                      .Where(mo => (bool)mo["IPEnabled"]) 
                      .Select(x=> new NetworkAdapterConfiguration(x))) 
         { 
          nics.Add(config.Description); 
         } 
        } 
       } 

       return nics.ToArray(); 
      } 

      /// <summary> 
      /// Set's the DNS Server of the local machine 
      /// </summary> 
      /// <param name="nicDescription">The full description of the network interface class</param> 
      /// <param name="dnsServers">Comma seperated list of DNS server addresses</param> 
      /// <remarks>Requires a reference to the System.Management namespace</remarks> 
      public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false) 
      { 
       using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
       { 
        using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances()) 
        { 
         foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)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; 
      } 

      /// <summary> 
      /// Restarts a given Network adapter 
      /// </summary> 
      /// <param name="nicDescription">The full description of the network interface class</param> 
      public static void RestartNetworkAdapter(string nicDescription) 
      { 
       using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter")) 
       { 
        using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances()) 
        { 
         foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)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; 
          } 
         } 
        } 
       } 
      } 

      /// <summary> 
      /// Get's the DNS Server of the local machine 
      /// </summary> 
      /// <param name="nicDescription">The full description of the network interface class</param> 
      public static string[] GetNameservers(string nicDescription) 
      { 
       using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
       { 
        using (var networkConfigs = networkConfigMng.GetInstances()) 
        { 
         foreach (var config in networkConfigs.Cast<ManagementObject>() 
                   .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription) 
                   .Select(x => new NetworkAdapterConfiguration(x))) 
         { 
          return config.DNSServerSearchOrder; 
         } 
        } 
       } 

       return null; 
      } 

      /// <summary> 
      /// Set's a new IP Address and it's Submask of the local machine 
      /// </summary> 
      /// <param name="nicDescription">The full description of the network interface class</param> 
      /// <param name="ipAddresses">The IP Address</param> 
      /// <param name="subnetMask">The Submask IP Address</param> 
      /// <param name="gateway">The gateway.</param> 
      /// <remarks>Requires a reference to the System.Management namespace</remarks> 
      public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway) 
      { 
       using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) 
       { 
        using (var networkConfigs = networkConfigMng.GetInstances()) 
        { 
         foreach (var config in networkConfigs.Cast<ManagementObject>() 
                     .Where(mo => (bool)mo["IPEnabled"] && (string)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 (!String.IsNullOrEmpty(gateway)) 
          { 
           config.SetGateways(new[] {gateway}, new ushort[] {1}); 
          } 
         } 
        } 
       } 
      } 

     } 
    } 

source complet: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs

+0

Bien que ce lien puisse répondre à la question, il est préférable d'inclure les parties essentielles de la réponse ici et fournir le lien pour référence. Les réponses à lien uniquement peuvent devenir invalides si la page liée change. - [À revoir] (/ review/low-quality-posts/11484927) –

+0

Très bon point Cyril, j'ai mis à jour ma réponse en conséquence. –

Questions connexes