netcore获取MAC地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// <summary>
/// 获取电脑 MAC地址
/// </summary>
/// <param name="separator"></param>
/// <returns></returns>
public static List<string> GetActiveMacAddress(string separator = "-")
{
    //本地计算机网络连接信息
    IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
    //获取本机电脑名
    var HostName = computerProperties.HostName;
    //获取域名
    var DomainName = computerProperties.DomainName;
    //获取本机所有网络连接
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
 
    var macAddress = new List<string>();
    if (nics == null || nics.Length < 1)
    {
        //Debug.WriteLine("  No network interfaces found.");
        return macAddress;
    }
 
    //Debug.WriteLine("  Number of interfaces .................... : {0}", nics.Length);
    foreach (NetworkInterface adapter in nics.Where(c =>
        c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up))
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
 
        var unicastAddresses = properties.UnicastAddresses;
        if (unicastAddresses.Any(temp => temp.Address.AddressFamily == AddressFamily.InterNetwork))
        {
            var address = adapter.GetPhysicalAddress();
 
            if (string.IsNullOrEmpty(separator))
            {
                macAddress.Add(address.ToString());
            }
            else
            {
                var MACIp = "";
                byte[] bytes = address.GetAddressBytes();
                for (int i = 0; i < bytes.Length; i++)
                {
                    MACIp += bytes[i].ToString("X2");
 
                    if (i != bytes.Length - 1)
                    {
                        MACIp += separator;
                    }
                }
 
                macAddress.Add(MACIp);
            }
        }
    }
    return macAddress;
}

  

posted @   86727515  阅读(745)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示