Get the MAC (Physical) address from a device at the specified IP address


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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. }

URL: http://www.codeproject.com/KB/IP/host_info_within_network.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.