本機信息與局域網信息的獲取,需要用到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進行判斷,局域網裡面的本網段主機: