通过 ManagementClass 类, 初始化 Win32_NetworkAdapterConfiguration 信息.
遍历结果获取 Description,IPEnabled,IPAddress,DefaultIPGateway,MACAddress等信息
/// <summary>
/// 获取网络适配器信息:名称,ip,网关,mac
/// </summary>
/// <returns></returns>
public static string GetNetworkAdapters()
{
ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objCol = mgmt.GetInstances();
List<ManagementObject> objList = new List<ManagementObject>();
foreach (ManagementObject obj in objCol)
{
objList.Add(obj);
}
objList = objList.OrderByDescending(o => (bool)o.Properties["IPEnabled"].Value == true).ToList();
StringBuilder sb = new StringBuilder();
uint i = 1;
foreach (ManagementObject obj in objList)
{
var d = obj["Description"]?.ToString();
var ipEnabled = obj["IPEnabled"];
var ip = obj["IPAddress"];
var gateway = obj["DefaultIPGateway"];
var mac = obj["MACAddress"];
if (ip != null)
{
if (((string[])ip).Length > 1)
{
ip = $"IP地址{((string[])ip)[0]}|{((string[])ip)[1]}";
}
else
{
ip = $"IP地址{((string[])ip)[0]}";
}
}
else
{
ip = $"IP地址暂无";
}
if (gateway != null)
{
gateway = $"网关{((string[])gateway)[0]}";
}
else
{
gateway = $"网关暂无";
}
if (mac != null)
{
mac = $"MAC地址{mac}";
}
else
{
mac = $"MAC地址暂无";
}
sb.AppendLine($"序号{i}>>{d},{ip},{gateway},{mac}");
sb.AppendLine();
i++;
}
return sb.ToString();
}
运行输出:
网络适配器:
序号1>>Realtek(R) PCI(e) Ethernet Controller,IP地址192.168.0.110|fe80::91e7:5ba2:f4ca:ed69,网关192.168.0.1,MAC地址FC:AA:14:D2:6C:58
序号2>>Microsoft Kernel Debug Network Adapter,IP地址暂无,网关暂无,MAC地址暂无
序号3>>WAN Miniport (SSTP),IP地址暂无,网关暂无,MAC地址暂无
序号4>>WAN Miniport (IKEv2),IP地址暂无,网关暂无,MAC地址暂无
序号5>>WAN Miniport (L2TP),IP地址暂无,网关暂无,MAC地址暂无
序号6>>WAN Miniport (PPTP),IP地址暂无,网关暂无,MAC地址暂无
序号7>>WAN Miniport (PPPOE),IP地址暂无,网关暂无,MAC地址暂无
序号8>>WAN Miniport (GRE),IP地址暂无,网关暂无,MAC地址暂无
序号9>>WAN Miniport (IP),IP地址暂无,网关暂无,MAC地址D2:95:20:52:41:53
序号10>>WAN Miniport (IPv6),IP地址暂无,网关暂无,MAC地址D4:FA:20:52:41:53
序号11>>WAN Miniport (Network Monitor),IP地址暂无,网关暂无,MAC地址D6:58:20:52:41:53
序号12>>蓝牙个人区域网络设备,IP地址暂无,网关暂无,MAC地址暂无
图片展示效果