2011-04-11 89 views
8

我正在嘗試創建一個將動態DHCP提供的IPv4地址,網關和dns設置轉換爲靜態配置的工具。我試圖用WMI來解決這個難題,但我有一個我無法弄清楚的問題。使用WMI EnableStatic方法的問題

應用程序完成後,配置了DNS和網關,但EnableStatic方法(設置IP地址和子網)沒有成功,這意味着即使缺省情況下仍從DHCP接收IP(使用灰色字段)網關已設置。我該如何解決?

EnableStatic的ReturnValue值爲70(無效的IP地址)。奇怪的是,輸入參數與我在2秒前從NIC中提取的參數相同。

下面是代碼(除GUI),http://pastebin.com/AE3dGhUz

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Management; 

namespace Static_NIC_Settings_Creator 
{ 
    public partial class Form1 : Form 
    { 
     private ManagementObjectCollection queryCollection; 
     private string[] networkInterfaces; 
     private int currentNIC; 
     private string[] ipAddress; 
     private string[] subnetMask; 
     private string[] defaultIPGateway; 
     private string[] dnsServerSearchOrder; 

     public Form1() 
     { 
      InitializeComponent(); 
      getNICs(); 
     } 

     private void convertButton_Click(object sender, EventArgs e) 
     { 
      if (networkInterfaces.Count() > 0) 
      { 
       //Get current NIC settings 
       if (!getNICSettings()) 
       { 
        MessageBox.Show("Retrieving current NIC settings failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
        return; 
       } 
       //Convert to static NIC settings 
       if (!setNICStatic()) 
       { 
        MessageBox.Show("Setting NIC settings to static failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
        return; 
       } 
      } 
     } 

     private void nicSelecter_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      currentNIC = nicSelecter.SelectedIndex; 
     } 

     private void getNICs() 
     { 
      //Get NICS 
      ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'"); 
      queryCollection = query.Get(); 
      //Make nic string array 
      int i = queryCollection.Count; 
      networkInterfaces = new string[i]; 
      //Fill nic string array 
      i = 0; 
      foreach (ManagementObject mo in queryCollection) 
      { 
       networkInterfaces[i] = (String)mo["Description"]; 
       i++; 
      } 
      //Fill dropbox with arraylist-data 
      nicSelecter.DataSource = networkInterfaces; 
     } 

     private Boolean getNICSettings() 
     { 
      //Get selected NIC 
      int i = 0; 
      foreach (ManagementObject mo in queryCollection) 
      { 
       //Get settings for specific NIC 
       if (i == currentNIC) 
       { 
        try 
        { 
         ipAddress = (String[])mo["IPAddress"]; 
         subnetMask = (String[])mo["IPSubnet"]; 
         defaultIPGateway = (String[])mo["DefaultIPGateway"]; 
         dnsServerSearchOrder = (String[])mo["DNSServerSearchOrder"]; 
         return true; 
        } 
        catch (Exception e) 
        { 
         System.Windows.Forms.MessageBox.Show(e.ToString(), "Critical: Unhandled error"); 
         return false; 
        } 
       } 
       i++; 
      } 
      return false; 
     } 

     private Boolean setNICStatic() 
     { 
      //Get selected NIC 
      int i = 0; 
      foreach (ManagementObject mo in queryCollection) 
      { 
       //Get settings for specific NIC 
       if (i == currentNIC) 
       { 
        try 
        { 
         //Set static IP and subnet mask 
         ManagementBaseObject setIP; 
         ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic"); 
         newIP["IPAddress"] = ipAddress; 
         newIP["SubnetMask"] = subnetMask; 
         setIP = mo.InvokeMethod("EnableStatic", newIP, null); 
         //Set default gateway 
         ManagementBaseObject setGateway; 
         ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways"); 
         newGateway["DefaultIPGateway"] = defaultIPGateway; 
         newGateway["GatewayCostMetric"] = new int[] { 1 }; 
         setGateway = mo.InvokeMethod("SetGateways", newGateway, null); 
         //Set dns servers 
         ManagementBaseObject setDNS; 
         ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder"); 
         newDNS["DNSServerSearchOrder"] = dnsServerSearchOrder; 
         setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); 

         System.Windows.Forms.MessageBox.Show("Setting NIC settings returned: " + setDNS); 
         return true; 
        } 
        catch (Exception e) 
        { 
         System.Windows.Forms.MessageBox.Show(e.ToString(), "Critical: Unhandled error"); 
         return false; 
        } 
       } 
       i++; 
      } 
      //No NICs 
      return false; 
     } 
    } //End class 
} 

任何想法?

回答

3

難道你也在輸入IPv6地址嗎?只是玩PowerShell似乎不喜歡它們。也許你可以發佈在調試時輸入的實際值,這會有很大的幫助。另外也許嘗試靜態輸入一些值,如:

new string[]{"192.168.0.1"}, new string[] {"255.255.255.255"} 

而且除非你真的需要C#和GUI,你可能要考慮使用PowerShell的(要求它正在安裝過程中)的WMI是真的要簡單得多在那裏操作(可惜你仍然有這種學習曲線)。

這僅僅是如何使用PowerShell的一個例子,你可以在最起碼使用它的一些測試:

Get-WmiObject Win32_NetworkAdapterConfiguration 

然後讓你的適配器的索引,然後運行,但取代你的索引號:

$obj = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.Index -eq 1} 
$obj.EnableStatic("192.168.0.1", "255.255.255.0") 

要獲得方法參數只需運行:

$obj.EnableStatic 

它將返回:

MemberType   : Method 
OverloadDefinitions : {System.Management.ManagementBaseObject EnableStatic(System.String[]IPAddress, System.String[] SubnetMask)} 
TypeNameOfValue  : System.Management.Automation.PSMethod 
Value    : System.Management.ManagementBaseObject EnableStatic(System.String[]IPAddress, System.String[] SubnetMask) 
Name    : EnableStatic 
IsInstance   : True 
+0

這是姍姍來遲。很久以前,我已經提出了這個問題,但現在當我在PS上練習時,我花了一些時間來測試C#應用程序。似乎有關於IP6的東西,所以我使用'newIP [「IPAddress」] = new String [] {ipAddress [0]};'和類似的子網只能獲得ipv4設置。無論如何,多個ipaddresses是不太可能的。 Great catch =) – 2013-01-19 18:10:15

+0

IPAddresses屬性的描述(https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx#properties)表示:「該屬性可以包含IPv6地址或IPv4地址「。現在,當你查詢它時,它似乎同時包含v4和v6地址,但也許它只在你嘗試更改它時計數(使用例如EnableStatic()。如果你在EnableStatic中使用混合地址, )。 – 2017-10-25 09:33:08