C# 更改网关IP

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SetNetworkAdapter();
}


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[] { "192.168.0.5", "192.168.0.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>
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("{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"];
string[] gateways = (string[])mo["DefaultIPGateway"];
string[] dnses = (string[])mo["DNSServerSearchOrder"];

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);
Console.WriteLine(" Gateways:");
foreach (string gw in gateways)
Console.WriteLine("\t'{0}'", gw);

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

}

posted @ 2012-08-09 16:25  放哨De老鼠  阅读(355)  评论(0编辑  收藏  举报