今天在工作群里看到别的部门采集现场设备数据,与设备厂商的对话。说是让设备厂商提供获取Mac地址的接口,一时没忍住说了一句,微软提供的Iphlpapi.dll链接库提供了发送APR的方法,可以拿到设备地址,结果别人直接无视,大写的尴尬。
注意:本文获取的是局域网内的远程设备地址,不是本机的地址。
使用ChatGPT配合C#随便写了个demo,记录一下,方便以后查阅。
复制
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string ipAddress = "10.248.1.50"; // 远程设备的IP地址
Console.WriteLine(getMacAddr_Remote(ipAddress));
Console.WriteLine("按下任意键继续...");
Console.ReadLine();
}
//下面一种方法可以获取远程的MAC地址
[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);
/// <summary>
/// SendArp获取MAC地址
/// </summary>
/// <param name="RemoteIP">目标机器的IP地址如(192.168.1.1)</param>
/// <returns>目标机器的mac 地址</returns>
public static string getMacAddr_Remote(string RemoteIP)
{
StringBuilder macAddress = new StringBuilder();
try
{
Int32 remote = inet_addr(RemoteIP);
Int64 macInfo = new Int64();
Int32 length = 6;
SendARP(remote, 0, ref macInfo, ref length);
string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
int x = 12;
for (int i = 0; i < 6; i++)
{
if (i == 5)
{
macAddress.Append(temp.Substring(x - 2, 2));
}
else
{
macAddress.Append(temp.Substring(x - 2, 2) + "-");
}
x -= 2;
}
return macAddress.ToString();
}
catch
{
return macAddress.ToString();
}
}
}
}
如果只是临时看看,那么可以使用命令提示符,输入arp -a | findstr “10.1.1.1”查询对应ip的设备Mac地址,arp命令在Linux系统仍然适用。Linux中将findstr换成 grep 即可。






评论 (0)