【问题标题】:C# - Get mac address in Universal AppsC# - 在通用应用程序中获取 mac 地址
【发布时间】:2016-03-09 22:45:45
【问题描述】:

我正在开发一个 Windows 10 通用应用程序,我需要获取运行通用应用程序的设备的网络适配器的 mac 地址。我看了一点 MSDN,但我找到了获取 mac 地址的方法,谁能帮我提供代码以获取 windows 10 通用应用程序中网络适配器的 mac 地址?

提前致谢。

【问题讨论】:

标签: c# win-universal-app uwp


【解决方案1】:

嗯,我写了一些东西,但我没有在移动设备上测试它,因为我目前没有,但我在我的 PC 和 Windows Mobile 10 模拟器上测试了它。

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;
    }
}

还有我的 AdapterInfo 类:

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

    public string Description { get; set; }

    public string Name { get; set; }

    public string MAC { get; set; }
}

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

【讨论】:

  • 将它部署到树莓派 3 上,它可以工作。太棒了,谢谢托马斯。我为 wifi 添加了另一种适配器类型,使用从我的树莓派返回的类型,const int MIB_IF_TYPE_WIFI = 71;
  • 访问 iphlpapi.dll 将使您的应用在 Windows 商店中被拒绝
【解决方案2】:

引自 MSDN Fourms 帖子“How can a Windows Store App access the MAC addresses of network adapter devices

通常,您无法通过设计从 Windows 应用商店应用获取系统特定信息。

支持一种特殊情况:Guidance on using the App Specific Hardware ID (ASHWID) to implement per-device app logic

Chuck Walbourn - MSFT 微软公司 (MSFT)

【讨论】:

  • 这很有用,但不清楚需要哪个“uses”子句才能使此代码正常工作。 UWP 应用程序上的“var HardwareID = HardwareIdentification.GetPackageSpecificToken”告诉我“当前上下文中不存在名称‘HardwareIdentification’”,因此我们需要添加正确的使用子句。在 UWP 上似乎不可用,即使添加了“使用 Windows.System.Profile”
【解决方案3】:

我知道这是一篇旧帖子,但对于新的冒险,此代码适用于 UWP x86 和 ARM(在 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;
}

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

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多