如何使用C#获取IP地址的物理(MAC)地址?

Iai*_*ain 11 c# networking

从C#开始,我想做相同的以下内容:

arp -a |findstr 192.168.1.254
Run Code Online (Sandbox Code Playgroud)

或者,答案可以调用SendARP函数并获得结果.

这将允许我的应用程序执行一些需要MAC地址的其他处理.

jop*_*jop 26

SendARP P/Invoke是这样的:

[DllImport("iphlpapi.dll", ExactSpelling=true)]
public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );
Run Code Online (Sandbox Code Playgroud)

PInvoke.NET有这个例子:

IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP address

byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;

if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0)
     throw new InvalidOperationException("SendARP failed.");

string[] str = new string[(int)macAddrLen];
for (int i=0; i<macAddrLen; i++)
     str[i] = macAddr[i].ToString("x2");

Console.WriteLine(string.Join(":", str));
Run Code Online (Sandbox Code Playgroud)

  • 我在使用Wireshark在Windows XP上测试时发现的这个答案需要了解的事项:1)如果IP/MAC地址对已经在ARP缓存中,则ARP请求数据包将不会在网络上发送,但SendARP仍然会返回它在缓存中的(可能是陈旧的)macAddress.2)如果仅使用单个线程,则此方法可能非常慢.使用单个线程循环遍历整个IP地址子网(例如192.168.1.x)需要250+秒(每个IP地址1秒).对于所有250多个地址,使其大规模多线程花费不到一秒钟. (2认同)