2008-10-16 20 views
57

मैं एक मशीन है कि अन्य मशीनों के एक बैकअप के रूप में इस्तेमाल किया जा करने के लिए एक जादूगर विकासशील हूँ में (आईपी पता, डीएनएस, WINS, होस्ट नाम) कोड के साथ। जब यह किसी मौजूदा मशीन को प्रतिस्थापित करता है, तो उसे प्रतिस्थापित होने वाले मशीन से मेल खाने के लिए अपना आईपी पता, DNS, WINS, और होस्ट नाम सेट करना होगा।आप नेटवर्क सेटिंग कैसे बदल सकते हैं सी #

वहाँ में .net (सी #) एक पुस्तकालय जो मुझे इस प्रोग्राम के करने की अनुमति देता है?

कई एनआईसी हैं, जिनमें से प्रत्येक को व्यक्तिगत रूप से सेट करने की आवश्यकता है।

संपादित

अपने उदाहरण के लिए आप TimothyP धन्यवाद। यह मुझे सही रास्ते पर ले गया और त्वरित जवाब अद्भुत था।

धन्यवाद balexandre। आपका कोड सही है। मैं एक भीड़ में था और पहले ही टिमोथीपी से जुड़े उदाहरण को अनुकूलित कर चुका था, लेकिन मुझे आपका कोड जल्द ही पसंद था।

मैंने कंप्यूटर नाम बदलने के लिए समान तकनीकों का उपयोग करके एक नियमित भी विकसित किया है। यदि आप अपडेट के बारे में सूचित होना चाहते हैं तो मैं इसे भविष्य में पोस्ट करूंगा इसलिए RSS feed पर इन प्रश्नों की सदस्यता लें। मैं इसे बाद में या सोमवार को कुछ सफाई के बाद प्राप्त कर सकता हूं।

उत्तर

77

बस कुछ ही मिनटों में यह बनाया:

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

बस सक्षमस्टैटिक की तरह, प्रोग्रामिंग रूप से आईपी को गतिशील पर स्विच करने का कोई तरीका है? EnableDynamic? मैं एक क्लिक के साथ एक स्थिर और गतिशील आईपी के बीच टॉगल करने के लिए एक उपकरण बनाना चाहता हूं। धन्यवाद। – aalaap

+6

रुचि रखने वालों के लिए, आप यहां इस प्रबंधन ऑब्जेक्ट पर सभी गुणों और विधियों की एक सूची पा सकते हैं: http://msdn.microsoft.com/en-us/library/aa394217.aspx – Paccc

+1

@balexandre हम सीमित कैसे काम कर सकते हैं उपभोक्ता खाता? – Eric

11

मुझे आशा है कि तुम मुझे एक उदाहरण है, पर भेज कोई आपत्ति नहीं है, लेकिन यह वास्तव में एक आदर्श उदाहरण है: http://www.codeproject.com/KB/cs/oazswitchnetconfig.aspx

+0

हम सीमित उपयोगकर्ता खाते के अंतर्गत व्यावहारिक कैसे बना सकते हैं? – Eric

+0

यह वास्तव में वास्तव में अच्छा और जानकारीपूर्ण है! – Kaitlyn

5

मुझे पसंद है WMILinq समाधान। जबकि आपकी समस्या के लिए नहीं वास्तव में समाधान है, यह का स्वाद नीचे खोजने के लिए:

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

इसलिए वस्तुओं निपटारा हो जाता है balexandre एक छोटे से कोड पुनर्स्थापन और सी # 3.5+ की नई भाषा सुविधाओं उपयोग किया जाता है (लिंक, var, आदि)। चर का नाम बदलकर अधिक सार्थक नामों में किया गया। मैंने कम WMI इंटरैक्शन के साथ अधिक कॉन्फ़िगरेशन करने में सक्षम होने के लिए कुछ फ़ंक्शंस भी विलय किए। मैंने WINS कोड हटा दिया क्योंकि मुझे अब WINS को कॉन्फ़िगर करने की आवश्यकता नहीं है। यदि आपको इसकी आवश्यकता हो तो WINS कोड जोड़ने के लिए स्वतंत्र महसूस करें।

मामले किसी के लिए पुनर्संशोधित/आधुनिकीकरण कोड मैं यहाँ समुदाय में वापस डाल दिया उपयोग करने के लिए पसंद करती है।

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

setNameservers फ़ंक्शन में शामिल पैरामीटर 'nic' क्या है? – clamp

+0

इसका नेटवर्क इंटरफेस का नाम (विवरण) है। आप NetworkInterface.GetAllNetworkInterfaces() का उपयोग कर उन्हें समझा सकते हैं। – Marc

+2

नोट: आपको सिस्टम के लिए एक संदर्भ जोड़ना होगा। अपनी परियोजना में प्रबंधन। – Jeff

1

गतिशील आईपी सी # में परिवर्तन ... बहुत आसान है

कृपया नीचे दिए गए कोड को देखो और जाएँ: http://microsoftdotnetsolutions.blogspot.in/2012/12/dynamic-ip-change-in-c.html

+0

यह भी एक अच्छा समाधान है! –

+0

हालांकि यह लिंक प्रश्न का उत्तर दे सकता है, लेकिन यहां उत्तर के आवश्यक हिस्सों को शामिल करना बेहतर है और संदर्भ के लिए लिंक प्रदान करना बेहतर है। लिंक किए गए पृष्ठ में परिवर्तन होने पर लिंक-केवल उत्तर अमान्य हो सकते हैं। - [समीक्षा से] (/ समीक्षा/कम गुणवत्ता वाली पोस्ट/18747472) – dferenc

0

मौजूदा जवाब काफी टूटी हुई कोड है। DNS विधि बिल्कुल काम नहीं करती है। यहां कोड है जिसका उपयोग मैंने अपने एनआईसी को कॉन्फ़िगर करने के लिए किया था:

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

थोड़ा और संक्षिप्त उदाहरण जो अन्य उत्तरों के शीर्ष पर बनाता है। मैंने कोड जनरेशन का लाभ उठाया जिसे विजुअल स्टूडियो के साथ भेज दिया गया ताकि अधिकांश अतिरिक्त आमंत्रण कोड को हटाया जा सके और इसके बजाय टाइप की गई वस्तुओं के साथ प्रतिस्थापित किया जा सके।

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

     } 
    } 

पूर्ण स्रोत: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs

+0

हालांकि यह लिंक प्रश्न का उत्तर दे सकता है, लेकिन यहां उत्तर के आवश्यक हिस्सों को शामिल करना बेहतर है और संदर्भ के लिए लिंक प्रदान करना बेहतर है। लिंक किए गए पृष्ठ में परिवर्तन होने पर लिंक-केवल उत्तर अमान्य हो सकते हैं। - [समीक्षा से] (/ समीक्षा/कम गुणवत्ता वाली पोस्ट/11484927) –

+0

बहुत अच्छा बिंदु सिरिल, मैंने तदनुसार अपना जवाब अपडेट कर दिया है। –

संबंधित मुद्दे