C#编程修改本机的IP,网关等

时间:2010年04月12日 点击:321

static void SetNetworkAdapter()
{
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;

//设置ip地址和子网掩码
inPar = mo.GetMethodParameters( "EnableStatic" );
inPar[
"IPAddress"] = new string[] { "10.22.21.111","192.168.10.9" };
inPar[
"SubnetMask"] = new string[] { "255.255.255.0","255.255.255.0" };
outPar
= mo.InvokeMethod( "EnableStatic", inPar, null );

//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar[
"DefaultIPGateway"] = new string[] { "10.22.21.1","192.168.10.1"};
outPar
= mo.InvokeMethod( "SetGateways", inPar, null );

//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar[
"DNSServerSearchOrder"] = new string[] {"179.32.42.4","179.32.42.5"};
outPar
= mo.InvokeMethod( "SetDNSServerSearchOrder" ,inPar,null);
break;
}

}


/**//// <summary>
/// 显示当前的ip,子网掩码,网关,DNS,网卡地址等信息
/// </summary>

static void ShowNetworkAdapterInfo()
{
Console.WriteLine(
"****** Current Network Adapter Information ******" );
ManagementClass mc
= new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc
= mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;

Console.WriteLine(
"\n SVC: '' MAC: []", (string) mo["Caption"],
(
string) mo["ServiceName"], (string) mo["MACAddress"] );

string[] addresses = (string[]) mo[ "IPAddress" ];
string[] subnets = (string[]) mo[ "IPSubnet" ];
string[] gateways = (string[]) mo["DefaultIPGateway"];
string[] dnses = (string[])mo["DNSServerSearchOrder"];

Console.WriteLine(
" Addresses :" );
foreach(string sad in addresses)
Console.WriteLine(
"\t''", sad );

Console.WriteLine(
" Subnets :" );
foreach(string sub in subnets )
Console.WriteLine(
"\t''", sub );
Console.WriteLine(
" Gateways:");
foreach(string gw in gateways )
Console.WriteLine(
"\t''", gw );

Console.WriteLine(
" DNS:");
foreach(string dns in dnses )
Console.WriteLine(
"\t''", dns );
}

}

赞助商链接

热门内容

相关内容

联系我们

联系方式