Search code examples
.netnetwork-programmingcompact-frameworkmac-address

Read MAC address from network adapter


I need to get the MAC address of a Windows Mobile device. Is it possible to do this without using, say, OpenNetCF, only by .NET Compact Framework? The solution is in C# (Visual Studio 2008, a smart device project).

Having read Read MAC Address from network adapter in .NET, I wanted to use the example by plinth, but there was no kernel32.dll on the device.

Is there aother way to get the MAC address in .NET Compact Framework, or how could I replace the following methods:

     [DllImport("Kernel32.dll", EntryPoint = "CopyMemory")]
     private static extern void ByteArray_To_IPAdapterInfo(ref AdapterInfo dst, Byte[] src, int size);
     [DllImport("Kernel32.dll", EntryPoint = "CopyMemory")]
     private static extern void IntPtr_To_IPAdapterInfo(ref AdapterInfo dst, IntPtr src, int size);

Solution

  • If you want to get the MAC address, but without using a library like OpenNETCF's SDF then you simply have to do the same thing it does in your own code. You need to P/Invoke GetAdaptersInfo, something like this:

    [DllImport("iphlpapi.dll", SetLastError = true)]
    public static extern int GetAdaptersInfo(byte[] pAdapterInfo, ref uint pOutBufLen);
    

    You'll want to call it once with a null first parameter to get the size, then allocate a byte array of the proper size and recall it. It will fill it with an array of IP_ADAPTER_INFO structs that you then parse for each adapter in the system. The Address member is what you're after for the MAC address.