public class ClassNetGetMac
{
public ClassNetGetMac()
{
}
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest,Int32 host,byte[] mac,ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
/// <summary>
/// 根据ip得到网卡mac地址
/// </summary>
/// <param name="ip">给出的ip地址</param>
/// <returns>对应ip的网卡mac地址</returns>
public static string GetMACByIP(string ip)
{
try
{
byte[] aa=new byte[6];
Int32 ldest= inet_addr(ip); //目的地的ip
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest,0, aa, ref len);
return BitConverter.ToString( aa, 0, 6 );;
}
catch(Exception err)
{
throw err;
}
}
}
博客给出了根据IP获取网卡MAC地址的代码实现。定义了ClassNetGetMac类,使用DllImport引入相关动态链接库函数,在GetMACByIP方法中,通过inet_addr获取目的地IP,调用SendARP函数获取MAC地址,若出现异常则抛出。
584

被折叠的 条评论
为什么被折叠?



