C#獲取IP/MAC地址
如果要想获得远程的地址,需要用sendarp这个函数来实现。具体的代码如下:
使用的命名空間:
using System.Runtime.InteropServices;
using System.Net;
using System.Management;
public class IPHelper
{
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
/// <summary>
/// 獲取當地的IP地址
/// </summary>
public static string GetLocalIP()
{
string strHostName = Dns.GetHostName(); //得到本机的主机名
IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
string strAddr = ipEntry.AddressList[0].ToString();
return (strAddr);
}
/// <summary>
/// 獲取當地MAC地址
/// </summary>
public static string GetLocalMac()
{
string mac = null;
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration"); ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (mo["IPEnabled"].ToString() == "True")
mac = mo["MacAddress"].ToString();
}
return (mac);
}
/// <summary>
/// 獲取遠程IP地址
/// </summary>
/// <param name="RemoteHostName"></param>
/// <returns></returns>
public static string[] GetRemoteIP(string RemoteHostName)
{
IPHostEntry ipEntry = Dns.GetHostByName(RemoteHostName);
IPAddress[] IpAddr = ipEntry.AddressList;
string[] strAddr = new string[IpAddr.Length];
for (int i = 0; i < IpAddr.Length; i++)
{
strAddr[i] = IpAddr[i].ToString();
}
return (strAddr);
}
/// <summary>
/// 獲取遠程MAC地址
/// </summary>
/// <param name="localIP"></param>
/// <param name="remoteIP"></param>
/// <returns></returns>
public static string GetRemoteMac(string localIP, string remoteIP)
{
Int32 ldest = inet_addr(remoteIP); //目的ip
Int32 lhost = inet_addr(localIP); //本地ip
try {
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
return Convert.ToString(macinfo, 16);
}
catch (Exception err)
{
Console.WriteLine("Error:{0}", err.Message);
}
return 0.ToString();
}
}
網上其他參考:http://www.cnblogs.com/qixuejia/archive/2011/01/12/1933442.html
http://www.cnblogs.com/diulela/archive/2012/04/07/2436111.html