利用 WMI 修改计算机的网络设置

类别:.NET开发 点击:0 评论:0 推荐:

利用 WMI 修改计算机的网络设置

Montaque(侯永锋)

申明:

    1、个人的一点心得,仅供参考
    2
、转载时候,请保留原本

 

概述:

                在前面的文章中,简要的介绍了如何利用 WMI 获取系统的软硬件设置,有兴趣的可以参考上篇文章(http://www.csdn.net/develop/read_article.asp?id=15744)。今天,我们就如何利用编程的方式读写系统的网络设置,主要包括本地网卡的 IP 地址、网络掩码以及 DNS 服务器和网关等。主要利用Win32_NetworkAdapterConfiguration WMI 类。

 

思路:

                ManagementObject 类表示数据管理对象,通过利用WQL(WMI Query Language) 筛选符合条件的管理对象,然后调用Win32_NetworkAdapterConfiguration 类的设置方法。对于 ManagementObject 对象,可以把调用方法的名称和参数传递给InvokeMethod 方法,以获得对管理对象类的方法调用。

 

                Win32_NetworkAdapterConfiguration 类包含了计算机网络适配器设置相关的一些属性和方法。该类支持与具体网络适配器无关的 TCP/IP 协议和 IPX 协议管理的一些方法和属性。

                下面列出了一些 Win32_NetworkAdapterConfiguration 的属性(托管对象格式)

 

        class Win32_NetworkAdapterConfiguration : CIM_Setting
{
  boolean ArpAlwaysSourceRoute;
  boolean ArpUseEtherSNAP;
  string Caption;
  string DatabasePath;
  boolean DeadGWDetectEnabled;
  string DefaultIPGateway[];
  uint8 DefaultTOS;
  uint8 DefaultTTL;
  string Description;
  boolean DHCPEnabled;
  datetime DHCPLeaseExpires;
  datetime DHCPLeaseObtained;
  string DHCPServer;
  string DNSDomain;
  string DNSDomainSuffixSearchOrder[];
  boolean DNSEnabledForWINSResolution;
  string DNSHostName;
  string DNSServerSearchOrder[];
  boolean DomainDNSRegistrationEnabled;
  uint32 ForwardBufferMemory;
  boolean FullDNSRegistrationEnabled;
  uint16 GatewayCostMetric[];
  uint8 IGMPLevel;
  uint32 Index;
  uint32 InterfaceIndex;
  string IPAddress[];
  uint32 IPConnectionMetric;
  boolean IPEnabled;
  boolean IPFilterSecurityEnabled;
  boolean IPPortSecurityEnabled;
  string IPSecPermitIPProtocols[];
  string IPSecPermitTCPPorts[];
  string IPSecPermitUDPPorts[];
  string IPSubnet[];
  boolean IPUseZeroBroadcast;
  string IPXAddress;
  boolean IPXEnabled;
  uint32 IPXFrameType[];
  uint32 IPXMediaType;
  string IPXNetworkNumber[];
  string IPXVirtualNetNumber;
  uint32 KeepAliveInterval;
  uint32 KeepAliveTime;
  string MACAddress;
  uint32 MTU;
  uint32 NumForwardPackets;
  boolean PMTUBHDetectEnabled;
  boolean PMTUDiscoveryEnabled;
  string ServiceName;
  string SettingID;
  uint32 TcpipNetbiosOptions;
  uint32 TcpMaxConnectRetransmissions;
  uint32 TcpMaxDataRetransmissions;
  uint32 TcpNumConnections;
  boolean TcpUseRFC1122UrgentPointer;
  uint16 TcpWindowSize;
  boolean WINSEnableLMHostsLookup;
  string WINSHostLookupFile;
  string WINSPrimaryServer;
  string WINSScopeID;
  string WINSSecondaryServer;
};

 

我们可以利用下列代码获取网卡的设置:

代码:

Imports System.Management

Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration ")

Dim share As ManagementObject

 For Each share In searcher.Get()

       MessageBox.Show(share.GetText(TextFormat.Mof))

 Next share

结果:

 

instance of Win32_NetworkAdapterConfiguration

{

       Caption = "[00000001] Intel(R) PRO/100 S Desktop Adapter";

       DatabasePath = "%SystemRoot%\\System32\\drivers\\etc";

       DefaultIPGateway = {"192.168.0.254"};   网关

       Description = "Intel(R) PRO/100 S Desktop Adapter"; 这个是惟一的

       DHCPEnabled = FALSE;

       DNSEnabledForWINSResolution = FALSE;

       DNSHostName = "monkey";

       DNSServerSearchOrder = {"192.168.0.254", "202.120.190.208"};  两个备选 DNS

       DomainDNSRegistrationEnabled = FALSE;

       FullDNSRegistrationEnabled = TRUE;

       GatewayCostMetric = {1};

       Index = 1;

       InterfaceIndex = 65539;

       IPAddress = {"192.168.0.161"};                  本地的 IP

       IPConnectionMetric = 20;

       IPEnabled = TRUE;

       IPFilterSecurityEnabled = FALSE;

       IPSecPermitIPProtocols = {"0"};

       IPSecPermitTCPPorts = {"0"};

       IPSecPermitUDPPorts = {"0"};

       IPSubnet = {"255.255.255.0"};                   掩码

       IPXEnabled = FALSE;

       MACAddress = "52:54:AB:DD:64:03";

       ServiceName = "E100B";

       SettingID = "{F5553268-53F8-48F6-A818-1432EEE04AE1}";

       TcpipNetbiosOptions = 0;

       WINSEnableLMHostsLookup = TRUE;

       WINSScopeID = "";

};

如何改变网卡的这些设置呢?我们直接利用 Win32_NetworkAdapterConfiguration 的一些方法。我们利用到的方法主要有以下:

EnableStatic

启用静态的 TCP/IP 设置,输入两个参数一个是本地
IP 地址,另外一个是网络掩码。

// 一般我们都是利用这个方法设置网卡的 IP 属性

SetGateways

指定一系列的网关

SetDNSServerSearchOrder

以数组的形式传入 DNS 列表

 

下面是一个 Snippet ,根据列表框显示的网卡 Description 的不同,设置对应地网卡。

 

主要的代码:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        GetAllConfigurationalleNetCard()

    End Sub

 

    修改设置

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description=""" & Me.ComboBox1.SelectedItem.ToString & """")

        Dim share As ManagementObject

 

        Dim iResult As Integer = 0 ‘ 判断是否修改成功。如果成功,后面的三个方法返回值都是0,注意返回的值是 Uint32 类型。

 

        For Each share In searcher.Get()

            Console.WriteLine(share.GetText(TextFormat.Mof))

            If Not (share.Item("IPAddress") Is Nothing) Then

              

                'set address

                Dim ipAddresses() As String = {TextBox1.Text} ‘ IP 地址

                Dim ipSubnetmask() As String = {TextBox2.Text} ‘掩码

                Dim objpara() As Object = {ipAddresses, ipSubnetmask}

                iResult += Convert.ToInt32(share.InvokeMethod("EnableStatic", objpara))

 

                Dim ipGateWay() As String = {TextBox3.Text} ‘网关

                Dim GatewayCostMetric() As UInt16 = {UInt16.Parse("1")}

                Dim objpara1() As Object = {ipGateWay, GatewayCostMetric}

                iResult += Convert.ToInt32(share.InvokeMethod("SetGateways", objpara1))

 

                'set Dns Server Serach Order

 

                多个dns 中间以减号分开

                If Me.TextBox4.Text.IndexOf("-") > 0 Then

                    Dim dnsServers As String() = TextBox4.Text.Split("-")

                    Dim objpara2() As Object = {dnsServers}

 

                    iResult += Convert.ToInt32(share.InvokeMethod("SetDNSServerSearchOrder", objpara2))

                Else

 

                    Dim dnsServers As String() = {Me.TextBox4.Text}

                    Dim objpara2() As Object = {dnsServers}

                    iResult += Convert.ToInt32(share.InvokeMethod("SetDNSServerSearchOrder", objpara2))

                End If

 

                If iResult = 0 Then

                    MessageBox.Show("修改成功")

                Else

                    MessageBox.Show("修改失败,检查输入的格式和您是否有权限")

                End If

 

            End If

        Next share

 

    End Sub

 

获取网卡列表

    Private Sub GetAllConfigurationalleNetCard()

        Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration")

        Dim share As ManagementObject

        Me.ComboBox1.Items.Clear()

        For Each share In searcher.Get()

            If Not (share.Item("IPAddress") Is Nothing) Then

                Me.ComboBox1.Items.Add(share("Description"))

            End If

        Next share

        Me.ComboBox1.SelectedIndex = 0

End Sub

 

获取网卡的详细信息

    Private Sub GetConfiguraton(ByVal description As String)

        If description Is Nothing Or description.Length = 0 Then

            Exit Sub

        Else

            Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description=""" & description & """")

            Dim share As ManagementObject

 

            For Each share In searcher.Get()

                Me.TextBox1.Text = DirectCast(share.Item("IPAddress"), String())(0).ToString

                Me.TextBox2.Text = DirectCast(share.Item("IPSubnet"), String())(0).ToString

                Me.TextBox3.Text = DirectCast(share.Item("DefaultIPGateway"), String())(0).ToString

                Dim i As Integer

                Me.TextBox4.Clear()

                For i = 0 To DirectCast(share.Item("DNSServerSearchOrder"), String()).GetLength(0) - 1

                    Me.TextBox4.Text &= DirectCast(share.Item("DNSServerSearchOrder"), String())(i).ToString & "-"

                Next

                If i >= 2 Then

                    Me.TextBox4.ForeColor = SystemColors.HotTrack

                Else

                    Me.TextBox4.ForeColor = Me.TextBox3.ForeColor

                End If

 

                Me.TextBox4.Text = Me.TextBox4.Text.Remove(Me.TextBox4.Text.Length - 1, 1)

 

                Me.TextBox5.Text = share.Item("MACAddress").ToString

                Exit For

            Next share

        End If

       

 

    End Sub

需要注意的地方:

  • InvokeMethod 传递的调用方法参数是 Object 类型,需要装箱操作。
  • EnableStatic SetGateways SetDNSServerSearchOrder 的返回值都是 Uint32,如果执行成功返回0,如果执行成功并且需要重启计算机则返回1
  • Win32_NetworkAdapterConfiguration 方法的这些属性一般都是只读的,调用管理对象的SetPropertyValue 方法无效。

 

参考:

ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/wmisdk/wmi/win32_networkadapterconfiguration.htm

如果需要详细的代码示例,请给我发 Email: [email protected] 请不要发超过100k的附件,否则直接被 Block 掉:)

2003-10-03 上海

本文地址:http://com.8s8s.com/it/it45355.htm