C# 修改IP、网关、DNS
1、在 “解决方案资源管理器” 右击 “引用” 添加 “System.Management” 的引用。
2、添加 “using System.Management;”。
static void SetNetworkAdapter()
{
ManagementBaseObject inPar = null;
ManagementBaseObject utPar = 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[] { "192.168.16.248", "192.168.16.249" };// 1.备用 2.IP
inPar["SubnetMask"] = new string[] { "255.255.255.0", "255.255.255.0" };
utPar = mo.InvokeMethod("EnableStatic", inPar, null);
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { "192.168.16.2", "192.168.16.254" }; // 1.网关;2.备用网关
utPar = mo.InvokeMethod("SetGateways", inPar, null);
//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[] { "211.97.168.129", "202.102.152.3" }; // 1.DNS 2.备用DNS
utPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
break;
}
}
2、添加 “using System.Management;”。
static void SetNetworkAdapter()
{
ManagementBaseObject inPar = null;
ManagementBaseObject utPar = 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[] { "192.168.16.248", "192.168.16.249" };// 1.备用 2.IP
inPar["SubnetMask"] = new string[] { "255.255.255.0", "255.255.255.0" };
utPar = mo.InvokeMethod("EnableStatic", inPar, null);
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { "192.168.16.2", "192.168.16.254" }; // 1.网关;2.备用网关
utPar = mo.InvokeMethod("SetGateways", inPar, null);
//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[] { "211.97.168.129", "202.102.152.3" }; // 1.DNS 2.备用DNS
utPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
break;
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/23109131/viewspace-694954/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/23109131/viewspace-694954/