/*******************************************************
* 求局域网内某IP地址所对应的MAC地址
* 原创者: www.mononet.cn
* 代码力求短小精干,已经在DotNet2.0环境下测试通过
* 欢迎使用和转载,但必须注明原创网址www.mononet.cn
********************************************************/
using System;
using System.Runtime.InteropServices;
public class test
{
public static unsafe string GetMAC(string rIpAddress)
{
try
{
// 初始化一些变量
Int32 ldest = inet_addr(rIpAddress); //目标主机的IP地址
int macLen = 8; //MAC地址长度,这里初始为8字节,API会返回真实的长度
byte[] macb = new byte[macLen]; //MAC地址
// 调用WINAPI
if (SendARP(ldest, 0, macb, &macLen) != 0) return "";
// 格式化MAC地址字串
string[] strMac = new string[macLen];
for (int i = 0; i < macLen; i++)
{
strMac[i] = macb[i].ToString("X2");
}
return string.Join("-", strMac);
}
catch
{
return "";
}
} //End GetMAC()
//必要的WINAPI支持
[DllImport("iphlpapi.dll")]
private static unsafe extern int SendARP(Int32 dest, Int32 host, byte[] mac, int* length);
[DllImport("ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
//应用示例
public static void Main(string[] args)
{
string ip = "";
if (args.Length < 1)
ip = "192.168.0.1";
else
ip = args[0];
string tmpstr = GetMAC(ip);
if (tmpstr != "")
Console.Write("IP: " + ip + " ===> MAC: " + tmpstr);
else
Console.WriteLine("找不到" + ip + "所对应的MAC地址!");
}
}
作者:mononet.cn 发布时间:08年02月12日 可选操作:
删除 回复