2012年1月29日 星期日

[C#] 取得 Mac And IP



寫Web常常需要抓IP,但MAC就比較少遇到了


網路卡號碼(MAC)

using System;
using System.Management;

public class MyClass
{
public static void Main()
{
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryMAC = query.Get();
foreach (ManagementObject mac in queryMAC)
{
if (mac["IPEnabled"].ToString() == "True")
Console.WriteLine(mac["MacAddress"].ToString());
}
}
}


本機IP

using System;
using System.Net;

public class MyClass
{
public static void Main()
{
IPHostEntry HostEntry = Dns.Resolve(Dns.GetHostName());
foreach (IPAddress ip in HostEntry.AddressList)
Console.WriteLine(ip.ToString());
}
}


ps. 如果找不到System.Management 去.NET元件找出來加入參考就好~!

沒有留言:

張貼留言