28 September 2017

How to get the MAC address of Any device on the network using C#

I once deployed a web application on a client that required to identify all the MAC addresses of different devices connected on the network. I can do arp -a command from command prompt, but I also created a short script to identify the MAC address of every device connected on the network using C#. Here's my code:

    [System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]
    private static extern int SendARP(int targetIp, int sourceIp, byte[] pcMacAddr, ref int macAddLength);
    public static PhysicalAddress GetMacAddress(IPAddress ipAddress)
    {
        const int macAddressLength = 6;
        int length = macAddressLength;
        var macBytes = new byte[macAddressLength];
        SendARP(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0), 0, macBytes, ref length);
        return new PhysicalAddress(macBytes);
    }

No comments:

Post a Comment