4

I am developing a Windows 10 Universal App, and I need to get the mac address of the network adapters of the device on which the universal app will run. I looked a bit into MSDN but I could find a way to get the mac address, can anyone help me out with the code to get the mac address of network adapters in universal apps for windows 10?

Thanks in advance.

Anna Jhaveri
  • 93
  • 2
  • 9
  • Does this help: http://stackoverflow.com/questions/850650/reliable-method-to-get-machines-mac-address-in-c-sharp – paul jerman Dec 04 '15 at 21:40
  • @pauljerman no it does not because you can't use any of the methods listed in that linked question in a Windows Universal App. – Scott Chamberlain Dec 04 '15 at 21:43
  • Possible duplicate of [How to get the mac address in WinRT (Windows 8) programmatically?](http://stackoverflow.com/questions/12892189/how-to-get-the-mac-address-in-winrt-windows-8-programmatically) – chue x Dec 04 '15 at 21:48

3 Answers3

8

Hmmm I wrote something but I didn't tested it on mobile device because I don't have any at the moment but I tested it on my PC and Windows Mobile 10 emulator.

public static class AdaptersHelper
{
    const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
    const int ERROR_BUFFER_OVERFLOW = 111;
    const int MAX_ADAPTER_NAME_LENGTH = 256;
    const int MAX_ADAPTER_ADDRESS_LENGTH = 8;
    const int MIB_IF_TYPE_OTHER = 1;
    const int MIB_IF_TYPE_ETHERNET = 6;
    const int MIB_IF_TYPE_TOKENRING = 9;
    const int MIB_IF_TYPE_FDDI = 15;
    const int MIB_IF_TYPE_PPP = 23;
    const int MIB_IF_TYPE_LOOPBACK = 24;
    const int MIB_IF_TYPE_SLIP = 28;

    [DllImport("iphlpapi.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
    public static extern int GetAdaptersInfo(IntPtr pAdapterInfo, ref Int64 pBufOutLen);

    public static List<AdapterInfo> GetAdapters()
    {
        var adapters = new List<AdapterInfo>();

        long structSize = Marshal.SizeOf(typeof(IP_ADAPTER_INFO));
        IntPtr pArray = Marshal.AllocHGlobal(new IntPtr(structSize));

        int ret = GetAdaptersInfo(pArray, ref structSize);

        if (ret == ERROR_BUFFER_OVERFLOW) // ERROR_BUFFER_OVERFLOW == 111
        {
            // Buffer was too small, reallocate the correct size for the buffer.
            pArray = Marshal.ReAllocHGlobal(pArray, new IntPtr(structSize));

            ret = GetAdaptersInfo(pArray, ref structSize);
        }

        if (ret == 0)
        {
            // Call Succeeded
            IntPtr pEntry = pArray;

            do
            {
                var adapter = new AdapterInfo();

                // Retrieve the adapter info from the memory address
                var entry = (IP_ADAPTER_INFO)Marshal.PtrToStructure(pEntry, typeof(IP_ADAPTER_INFO));

                // Adapter Type
                switch (entry.Type)
                {
                    case MIB_IF_TYPE_ETHERNET:
                        adapter.Type = "Ethernet";
                        break;
                    case MIB_IF_TYPE_TOKENRING:
                        adapter.Type = "Token Ring";
                        break;
                    case MIB_IF_TYPE_FDDI:
                        adapter.Type = "FDDI";
                        break;
                    case MIB_IF_TYPE_PPP:
                        adapter.Type = "PPP";
                        break;
                    case MIB_IF_TYPE_LOOPBACK:
                        adapter.Type = "Loopback";
                        break;
                    case MIB_IF_TYPE_SLIP:
                        adapter.Type = "Slip";
                        break;
                    default:
                        adapter.Type = "Other/Unknown";
                        break;
                } // switch

                adapter.Name = entry.AdapterName;
                adapter.Description = entry.AdapterDescription;

                // MAC Address (data is in a byte[])
                adapter.MAC = string.Join("-", Enumerable.Range(0, (int)entry.AddressLength).Select(s => string.Format("{0:X2}", entry.Address[s])));

                // Get next adapter (if any)

                adapters.Add(adapter);

                pEntry = entry.Next;
            }
            while (pEntry != IntPtr.Zero);

            Marshal.FreeHGlobal(pArray);
        }
        else
        {
            Marshal.FreeHGlobal(pArray);
            throw new InvalidOperationException("GetAdaptersInfo failed: " + ret);
        }

        return adapters;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct IP_ADAPTER_INFO
    {
        public IntPtr Next;
        public Int32 ComboIndex;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ADAPTER_NAME_LENGTH + 4)]
        public string AdapterName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ADAPTER_DESCRIPTION_LENGTH + 4)]
        public string AdapterDescription;
        public UInt32 AddressLength;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_ADAPTER_ADDRESS_LENGTH)]
        public byte[] Address;
        public Int32 Index;
        public UInt32 Type;
        public UInt32 DhcpEnabled;
        public IntPtr CurrentIpAddress;
        public IP_ADDR_STRING IpAddressList;
        public IP_ADDR_STRING GatewayList;
        public IP_ADDR_STRING DhcpServer;
        public bool HaveWins;
        public IP_ADDR_STRING PrimaryWinsServer;
        public IP_ADDR_STRING SecondaryWinsServer;
        public Int32 LeaseObtained;
        public Int32 LeaseExpires;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct IP_ADDR_STRING
    {
        public IntPtr Next;
        public IP_ADDRESS_STRING IpAddress;
        public IP_ADDRESS_STRING IpMask;
        public Int32 Context;
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct IP_ADDRESS_STRING
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
        public string Address;
    }
}

And my AdapterInfo class:

public class AdapterInfo
{
    public string Type { get; set; }

    public string Description { get; set; }

    public string Name { get; set; }

    public string MAC { get; set; }
}

source: http://www.pinvoke.net/default.aspx/iphlpapi/GetAdaptersInfo.html

Tomasz Pikć
  • 753
  • 5
  • 21
  • 1
    deployed this to a raspberry pi 3, and it works. brilliant, thanks Tomasz. I added another adapter type for wifi, using the type that came back from my raspberry pi, const int MIB_IF_TYPE_WIFI = 71; – Mike Jan 01 '17 at 17:27
  • acessing iphlpapi.dll will make your app get rejected in windows store – suvish valsan Nov 19 '17 at 10:59
5

Quoting from the MSDN Fourms post "How can a Windows Store App access the MAC addresses of network adapter devices"

In general you don't have a way to get system-specific information from Windows Store apps by design.

There is a special case that is supported: Guidance on using the App Specific Hardware ID (ASHWID) to implement per-device app logic

Chuck Walbourn - MSFT Microsoft Corp (MSFT)

Community
  • 1
  • 1
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • This is useful, except it's unclear which "uses" clause is required to make this code work. "var HardwareID = HardwareIdentification.GetPackageSpecificToken" on an UWP app tells me "The name 'HardwareIdentification' does not exist in the current context", thus we need to add the correct uses clause. Seems unavailable on UWP, even after adding "using Windows.System.Profile" – T.S Jun 15 '17 at 15:09
1

I know this is an old post, but for new adventures, this code works on UWP x86 and ARM (tested on a raspberry 3)

static string GetMacAddress()
{
    string macAddresses = "";
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        // Only consider Ethernet network interfaces, thereby ignoring any
        // loopback devices etc.
        if (nic.NetworkInterfaceType != NetworkInterfaceType.Ethernet) continue;
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            macAddresses += nic.GetPhysicalAddress().ToString();
            break;
        }
    }
    return macAddresses;
}

Source: http://www.independent-software.com/getting-local-machine-mac-address-in-csharp.html

robbi
  • 21
  • 3