摘自:如何编程实现修改IP地址、子网掩码、网关、DNS地址等?
具体参考下面的完整代码。
using System;
using System.Management;
using System.Threading;
namespace WmiIpChanger
{
class IpChanger
{
[MTAThread]
static void Main(string[] args)
{
ReportIP();
// SwitchToDHCP();
SwitchToStatic();
Thread.Sleep( 5000 );
ReportIP();
Console.WriteLine( "end." );
}
static void SwitchToDHCP()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo["IPEnabled"] )
continue;
inPar = mo.GetMethodParameters("EnableDHCP");
outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
break;
}
}
static void SwitchToStatic()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
inPar = mo.GetMethodParameters( "EnableStatic" );
inPar["IPAddress"] = new string[] { "192.168.1.1" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod( "EnableStatic", inPar, null );
break;
}
}
static void ReportIP()
{
Console.WriteLine( "****** Current IP addresses:" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
Console.WriteLine( "{0}\n SVC: '{1}' MAC: [{2}]", (string) mo["Caption"],
(string) mo["ServiceName"], (string) mo["MACAddress"] );
string[] addresses = (string[]) mo[ "IPAddress" ];
string[] subnets = (string[]) mo[ "IPSubnet" ];
Console.WriteLine( " Addresses :" );
foreach(string sad in addresses)
Console.WriteLine( "\t'{0}'", sad );
Console.WriteLine( " Subnets :" );
foreach(string sub in subnets )
Console.WriteLine( "\t'{0}'", sub );
}
}
}
}
本文作者:佚名 来源:http://faq.lvjiyong.com/item/2101/
CIO之家 www.ciozj.com 微信公众号:imciow
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。