[DllImport("Iphlpapi.dll")]
static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
[DllImport("Ws2_32.dll")]
static extern Int32 inet_addr(string ipaddr);
//SendArp获取MAC地址
public static string GetMacAddress(string macip)
{
StringBuilder strReturn = new StringBuilder();
try
{
Int32 remote = inet_addr(macip);
Int64 macinfo = new Int64();
Int32 length = 6;
SendARP(remote, 0, ref macinfo, ref length);
string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
int x = 12;
for (int i = 0; i < 6; i++)
{
if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); }
else { strReturn.Append(temp.Substring(x - 2, 2) + ":"); }
x -= 2;
}
return strReturn.ToString();
}
catch
{
return strReturn.ToString();
}
}
本文介绍了一种使用C#语言通过指定IP地址来获取对应MAC地址的方法。该方法利用了SendARP函数从Iphlpapi.dll库以及inet_addr函数从Ws2_32.dll库。通过将IP地址转换为整数并调用SendARP函数,可以获取到目标设备的MAC地址,并将其格式化为标准的十六进制字符串。
4517

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



