C# 本机信息与局域网信息的获取
本机信息与局域网信息的获取,需要用到Management这个类,这个类的功能十分强大,可以实现的事情也很多,下面我来列举部分实现本机与局域网信息的例子。
首先对项目添加System.Management引用,然后在代码上面输入using System.Management
下面来看看如何取得本机信息:
private static string ipAddress = "";
static void Main(string[] args)
{
string macAddress = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection mac = mc.GetInstances();
foreach (ManagementObject mo in mac)
{
if ((bool)mo["IPEnabled"] == true)
{
macAddress += mo["MacAddress"].ToString();
}
}
macAddress = macAddress.Replace(:, -);
IPAddress[] ipAddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
for (int i = 0; i < ipAddressList.Length; i++)
{
ipAddress += ipAddressList[i].ToString();
}
Console.WriteLine(macAddress); //MacAddress
Console.WriteLine(ipAddress); //IPAddress
Console.WriteLine(Dns.GetHostName()); //HostName
Console.WriteLine(Environment.UserName); //UserName
Console.WriteLine(Environment.UserDomainName); //DomainName
Console.ReadLine();
}
上面有代码会输出如下信息:
00-1E-C9-29-59-D7
192.168.1.1
NON-Alex
Alex
CompanyLan
下面是通过IP进行判断,局域网里面的本网段主机: