使用 WMI 和 C# 配置 TCP/IP 设置






4.35/5 (25投票s)
2003 年 12 月 23 日

299367

6917
使用 WMI 和 C# 配置 TCP/IP 设置
引言
本文演示了 WMI 的强大功能,展示了如何使用 C# 以编程方式配置 TCP/IP 设置。本文面向中级开发人员。
使用代码
WMI 扩展了 .NET 的可能性,并在处理 NetworkAdapters
时简化了工作。以下代码片段列出了所有网络适配器以及 IP 地址、子网掩码和默认网关。
public void ListIP()
{
ManagementClass objMC = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach(ManagementObject objMO in objMOC)
{
if(!(bool)objMO["ipEnabled"])
continue;
Console.WriteLine(objMO["Caption"] + "," +
objMO["ServiceName"] + "," + objMO["MACAddress"]) ;
string[] ipaddresses = (string[]) objMO["IPAddress"];
string[] subnets = (string[]) objMO["IPSubnet"];
string[] gateways = (string[]) objMO["DefaultIPGateway"];
Console.WriteLine("Printing Default Gateway Info:");
Console.WriteLine(objMO["DefaultIPGateway"].ToString());
Console.WriteLine("Printing IPGateway Info:");
foreach(string sGate in gateways)
Console.WriteLine (sGate);
Console.WriteLine("Printing Ipaddress Info:");
foreach(string sIP in ipaddresses)
Console.WriteLine(sIP);
Console.WriteLine("Printing SubNet Info:");
foreach(string sNet in subnets)
Console.WriteLine(sNet);
}
现在,以下是使用 WMI 配置 TCP/IP 设置的代码。
public void setIP(string IPAddress,string SubnetMask, string Gateway)
{
ManagementClass objMC = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach(ManagementObject objMO in objMOC)
{
if (!(bool) objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] {Gateway};
objNewGate["GatewayCostMetric"] = new int[] {1};
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] {IPAddress};
objNewIP["SubnetMask"] = new string[] {SubnetMask};
objSetIP = objMO.InvokeMethod("EnableStatic",objNewIP,null);
objSetIP = objMO.InvokeMethod("SetGateways",objNewGate,null);
Console.WriteLine(
"Updated IPAddress, SubnetMask and Default Gateway!");
}
catch(Exception ex)
{
MessageBox.Show("Unable to Set IP : " + ex.Message); }
}
Win32_NetworkAdapterConfiguration
WMI 类中包含一些有趣的方法,这些方法代表网络适配器的行为和属性,请在 http://msdn.microsoft.com/library/en-us/wmisdk/wmi/ 处探索它们。