Posted By

pckujawa on 06/01/11


Tagged

mac networking ipAddress


Versions (?)

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


 / Published in: C#
 

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

This is about the simplest way I've found. See this and this 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. }

Report this snippet  

You need to login to post a comment.