从指定IP地址的设备获取MAC(物理)地址

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从指定IP地址的设备获取MAC(物理)地址相关的知识,希望对你有一定的参考价值。

This is about the simplest way I've found. See [this](http://stackoverflow.com/questions/1092463/getting-the-mac-address-of-the-remote-host) and [this](http://stackoverflow.com/questions/1092379/want-to-get-mac-address-of-remote-pc/1092392#1092392) at StackOverflow for more info.
  1. using System.Net;
  2. using System.Net.NetworkInformation;
  3.  
  4. /// <summary>
  5. /// Holds utilities for working with networks, Ethernet, etc.
  6. /// </summary>
  7. public static class NetworkUtils
  8. {
  9. // http://www.codeproject.com/KB/IP/host_info_within_network.aspx
  10. [System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]
  11. static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref int PhyAddrLen);
  12.  
  13. /// <summary>
  14. /// Gets the MAC address (<see cref="PhysicalAddress"/>) associated with the specified IP.
  15. /// </summary>
  16. /// <param name="ipAddress">The remote IP address.</param>
  17. /// <returns>The remote machine's MAC address.</returns>
  18. public static PhysicalAddress GetMacAddress(IPAddress ipAddress)
  19. {
  20. const int MacAddressLength = 6;
  21. int length = MacAddressLength;
  22. var macBytes = new byte[MacAddressLength];
  23. SendARP(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0), 0, macBytes, ref length);
  24. return new PhysicalAddress(macBytes);
  25. }
  26. }
  27.  
  28.  
  29. [TestClass()]
  30. public class NetworkUtilsTests
  31. {
  32. [TestMethod()]
  33. public void GetMacAddress_BroadcastIP_NonzeroMac()
  34. {
  35. IPAddress ipAddress = IPAddress.Broadcast;
  36.  
  37. PhysicalAddress actual = NetworkUtils.GetMacAddress(ipAddress);
  38. Console.WriteLine(actual.ToString());
  39.  
  40. Assert.AreNotEqual(PhysicalAddress.None, actual);
  41. }
  42. }

以上是关于从指定IP地址的设备获取MAC(物理)地址的主要内容,如果未能解决你的问题,请参考以下文章

电脑的物理地址是MAC地址吗,为啥

如何在 Android 上以编程方式从 Mac 地址获取 IP 地址?

从 MAC 地址获取 IP。 arp -a 不显示设备

??如何从 mac 和 iPhone 获取路由器 IP 地址? [关闭]

php怎样获取客户端电脑物理地址

linux下怎样获取网络设备的mac地址,ip地址等