[指导]C 设置本地连接的IP地址
C# 设置本地连接的IP地址
因为我实在是太懒了,每次在实验室和寝室切换上网时都需要重设IP,烦啊。。。
下面这个程序实现了固定IP的设置(配置文件config.xml)和DHCP
的切换。
顺便学习了一下xml文件的读取和WMI的使用技巧,懒人有懒福呵(?:?b汗)
代码如下:
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Management;
using System.Net.NetworkInformation; using System.Text.RegularExpressions; using System.Xml;
using System.Windows.Forms; namespace IpTransferTool
{
public partial class Form1 : Form
{
private string[] ip;
private string[] submask;
private string[] getway;
private string[] dns;
public Form1()
{
InitializeComponent();
LoadConfigXml();
}
private void LoadConfigXml()
{
XmlNodeReader reader = null;
try
{
string eleName = "";
XmlDocument doc = new XmlDocument();
doc.Load("config.xml");
reader = new XmlNodeReader(doc);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
eleName = reader.Name;
//MessageBox.Show("Name" + eleName);
break;
case XmlNodeType.Text:
if (eleName.Equals("ip"))
{
ip = new string[1] { reader.Value };
}
else if
(eleName.Equals("submask"))
{
submask = new string[1] { reader.Value };
}
else if
(eleName.Equals("getway"))
{
getway = new string[1] { reader.Value };
}
else if (eleName.Equals("dns1"))
{
dns = new string[2] { reader.Value, "" };
}
else if (eleName.Equals("dns2"))
{
dns[1] = reader.Value;
}
//eleName = reader.Value;
//MessageBox.Show("Value" + eleName);
break;
default:
break;
}
}
}
catch
{
MessageBox.Show("load xml error.");
}
finally
{
if (reader != null)
reader.Close();
}
}
private void bAutoIP_Click(object sender, EventArgs
e)
{
try
{
EnableDHCP();
}
catch
{
MessageBox.Show("EnableDHCP() error.");
}
}
private void bSpecialIP_Click(object sender,
EventArgs e)
{
try
{
//ip = new string[1]{"192.168.2.119"};
//submask = new string[1]{"255.255.255.0"};
//getway = new string[1] {"192.168.2.2"};
//dns = new string[2] { "211.68.71.4", "211.68.71.5" };
SetIPAddress(ip,submask ,getway ,dns);
}
catch
{
MessageBox.Show("Special IP transfer error.");
}
}
///
/// 设置DNS
///
///
public static void SetDNS(string[] dns)
{
SetIPAddress(null, null, null, dns);
}
///
/// 设置网关
///
///
public static void SetGetWay(string getway)
{
SetIPAddress(null, null, new string[] { getway },
null);
}
///
/// 设置网关
///
///
public static void SetGetWay(string[] getway)
{
SetIPAddress(null, null, getway, null);
}
///
/// 设置IP地址和掩码
///
///
///
public static void SetIPAddress(string ip, string submask)
{
SetIPAddress(new string[] { ip }, new string[] { submask }, null, null);
}
///
/// 设置IP地址,掩码和网关
///
///
///
///
public static void SetIPAddress(string ip, string
submask, string getway)
{
SetIPAddress(new string[] { ip }, new string[]
{ submask }, new string[] { getway }, null);
}
///
/// 设置IP地址,掩码,网关和DNS
///
///
///
///
///
public static void SetIPAddress(string[] ip, string[]
submask, string[] getway, string[] dns)
{
ManagementClass wmi = new
ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = wmi.GetInstances();
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
foreach (ManagementObject mo in moc)
{
if
(!mo["Caption"].ToString().Equals("[00000012] Realtek RTL8168/8111 PCI-E Gigabit Ethernet NIC"))
continue;
else
MessageBox.Show((string)mo["caption"]);
//如果没有启用IP设置的网络设备则跳过
if (!(bool) mo["IPEnabled"])
continue;
//设置IP地址和掩码
if (ip != null && submask != null)
{
inPar =
mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = ip;
inPar["SubnetMask"] = submask;
outPar = mo.InvokeMethod("EnableStatic",
inPar, null);
}
//设置网关地址
if (getway != null)
{
inPar =
mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = getway;
outPar = mo.InvokeMethod("SetGateways", inPar, null);
}
//设置DNS地址
if (dns != null)
{
inPar =
mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = dns;
outPar =
mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
}
}
}
///
/// 启用DHCP服务器
///
public static void EnableDHCP()
{
ManagementClass wmi = new
ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = wmi.GetInstances();
foreach (ManagementObject mo in moc)
{
if
(!mo["Caption"].ToString().Equals("[00000012] Realtek RTL8168/8111 PCI-E Gigabit Ethernet NIC"))
continue;
else
MessageBox.Show((string)mo["caption"]);
//如果没有启用IP设置的网络设备则跳过
if (!(bool) mo["IPEnabled"])
continue;
//重置DNS为空
mo.InvokeMethod("SetDNSServerSearchOrder",
null);
//开启DHCP
mo.InvokeMethod("EnableDHCP", null);
}
}
///
/// 判断是否IP地址格式
///
///
///
public static bool IsIPAddress(string ip)
{
string[] arr = ip.Split('.');
if (arr.Length != 4)
return false;
string pattern = @"\d{1,3}";
for (int i = 0; i < arr.Length; i++)
{
string d = arr[i];
if (i == 0 && d == "0")
return false;
if (!Regex.IsMatch(d, pattern))
return false;
if (d != "0")
{
d = d.TrimStart('0');
if (d == "")
return false;
if (int.Parse(d) > 255)
return false;
}
}
return true;
}
}
}