Getting the MAC Address for a Machine on the Network

I was working on some code recently where I needed to get the MAC Address for a particular IP Address on the network. I settled on this snippet below. I thought I would share it. It uses a native call to the SendARP method in the iphlpapi.dll. The description below states what the SendARP method does according to the MSDN Documentation.

The SendARP function sends an Address Resolution Protocol (ARP) request to obtain the physical address that corresponds to the specified destination IPv4 address.

This snippet worked for IP4 addresses which was all I needed. I haven’t tried to solve this for IP6 addresses yet. If you have done this for IP6 then it would be great if you can leave a comment.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;

namespace Utility
{
    public sealed class NativeMethods
    {
        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        private static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

        private NativeMethods() { }

        public static string GetMacAddress(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                throw new ArgumentNullException("ipAddress");
            }

            IPAddress IP = IPAddress.Parse(ipAddress);
            byte[] macAddr = new byte[6];
            uint macAddrLen = (uint)macAddr.Length;

            if (SendARP((int)IP.Address, 0, macAddr, ref macAddrLen) != 0)
            {
                throw new CardVaultException("ARP command failed");
            }

            string[] str = new string[(int)macAddrLen];

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

            return string.Join(":", str).ToUpper();
        }
    }
}
Participate with Coding in the Trenches on Facebook

Participate with Coding in the Trenches on Facebook by Click the button above.

One thought on “Getting the MAC Address for a Machine on the Network

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s