You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.7 KiB
74 lines
2.7 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.NetworkInformation;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace AIK.Common.SysCommon
|
|
{
|
|
public static class MacAddressHelper
|
|
{
|
|
/// <summary>
|
|
/// 获取主物理网卡的 MAC 地址(格式:00-1A-2B-3C-4D-5E)
|
|
/// </summary>
|
|
public static string GetPrimaryMacAddress()
|
|
{
|
|
try
|
|
{
|
|
var activeAdapters = NetworkInterface
|
|
.GetAllNetworkInterfaces()
|
|
.Where(nic =>
|
|
nic.OperationalStatus == OperationalStatus.Up &&
|
|
nic.NetworkInterfaceType is NetworkInterfaceType.Ethernet or NetworkInterfaceType.Wireless80211 &&
|
|
!IsVirtualOrLoopback(nic))
|
|
.OrderByDescending(nic => nic.Speed) // 优先有线 > 无线
|
|
.ToList();
|
|
|
|
var primary = activeAdapters.FirstOrDefault()
|
|
?? NetworkInterface.GetAllNetworkInterfaces()
|
|
.FirstOrDefault(nic => !IsVirtualOrLoopback(nic));
|
|
|
|
if (primary?.GetPhysicalAddress().GetAddressBytes().Length > 0 is true)
|
|
{
|
|
return FormatMacAddress(primary.GetPhysicalAddress().GetAddressBytes());
|
|
}
|
|
|
|
return "未检测到有效物理网卡";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return $"获取失败: {ex.Message}";
|
|
}
|
|
}
|
|
|
|
private static bool IsVirtualOrLoopback(NetworkInterface nic)
|
|
{
|
|
if (nic.NetworkInterfaceType == NetworkInterfaceType.Loopback)
|
|
return true;
|
|
|
|
string desc = nic.Description.ToLowerInvariant();
|
|
return desc.Contains("virtual") ||
|
|
desc.Contains("vmware") ||
|
|
desc.Contains("vbox") ||
|
|
desc.Contains("hyper-v") ||
|
|
desc.Contains("bluetooth") ||
|
|
desc.Contains("tunnel") ||
|
|
desc.Contains("isatap") ||
|
|
desc.Contains("6to4") ||
|
|
desc.Contains("teredo");
|
|
}
|
|
|
|
private static string FormatMacAddress(ReadOnlySpan<byte> macBytes)
|
|
{
|
|
// 使用 Span 高效构建格式化字符串(.NET 8 推荐)
|
|
var result = new StringBuilder(macBytes.Length * 3 - 1);
|
|
for (int i = 0; i < macBytes.Length; i++)
|
|
{
|
|
if (i > 0) result.Append('-');
|
|
result.Append($"{macBytes[i]:X2}");
|
|
}
|
|
return result.ToString();
|
|
}
|
|
}
|
|
}
|
|
|