static class MacAddressProvider
{
const int PING_TIMEOUT = 1000;
[DllImport("iphlpapi.dll", ExactSpelling = true)]
static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
// *********************************************************************
/// <summary>
/// Gets the MAC address from ARP table in colon (:) separated format.
/// </summary>
/// <param name="hostNameOrAddress">Host name or IP address of the
/// remote host for which MAC address is desired.</param>
/// <returns>A string containing MAC address; null if MAC address could
/// not be found.</returns>
public static string GetMACAddressFromARP(string hostNameOrAddress)
{
if (!IsHostAccessible(hostNameOrAddress))
return null;
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
if (hostEntry.AddressList.Length == 0)
return null;
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
if (SendARP((int)hostEntry.AddressList[0].Address, 0, macAddr, ref macAddrLen) != 0)
return null;
StringBuilder macAddressString = new StringBuilder();
for (int i = 0; i < macAddr.Length; i++)
{
if (macAddressString.Length > 0)
macAddressString.Append(":");
macAddressString.AppendFormat("{0:x2}", macAddr[i]);
}
return macAddressString.ToString();
}
// *********************************************************************
/// <summary>
/// Checks to see if the host specified by
/// <paramref name="hostNameOrAddress"/> is currently accessible.
/// </summary>
/// <param name="hostNameOrAddress">Host name or IP address of the
/// remote host for which MAC address is desired.</param>
/// <returns><see langword="true" /> if the host is currently accessible;
/// <see langword="false"/> otherwise.</returns>
private static bool IsHostAccessible(string hostNameOrAddress)
{
Ping ping = new Ping();
PingReply reply = ping.Send(hostNameOrAddress, PING_TIMEOUT);
return reply.Status == IPStatus.Success;
}
}
|