分享
 
 
 

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

王朝other·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

利用 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: Rainman_am_I@hotmail.com 请不要发超过100k的附件,否则直接被 Block 掉:)

2003-10-03 上海

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有