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

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

利用 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

</