C#实现获取MAC地址的方法

这篇文章主要介绍了C#实现获取MAC地址的方法,很实用的功能,需要的朋友可以参考下

本文实例讲述了C#实现获取MAC地址的方法,是一个非常常见而且实用的功能,具体方法如下:

主要功能代码如下:

 ///  /// 根据网卡类型来获取mac地址 ///  /// 网卡类型 /// 格式化获取到的mac地址 /// 获取到的mac地址 public static string GetMacAddress(NetworkInterfaceType networkType, Func macAddressFormatHanlder) { string _mac = string.Empty; NetworkInterface[] _networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in _networkInterfaces) { if (adapter.NetworkInterfaceType == networkType) { _mac = adapter.GetPhysicalAddress().ToString(); if (!String.IsNullOrEmpty(_mac)) break; } } if (macAddressFormatHanlder != null) _mac = macAddressFormatHanlder(_mac); return _mac; } ///  /// 根据网卡类型以及网卡状态获取mac地址 ///  /// 网卡类型 /// 网卡状态 ///Up 网络接口已运行,可以传输数据包。 ///Down 网络接口无法传输数据包。 ///Testing 网络接口正在运行测试。 ///Unknown 网络接口的状态未知。 ///Dormant 网络接口不处于传输数据包的状态;它正等待外部事件。 ///NotPresent 由于缺少组件(通常为硬件组件),网络接口无法传输数据包。 ///LowerLayerDown 网络接口无法传输数据包,因为它运行在一个或多个其他接口之上,而这些“低层”接口中至少有一个已关闭。 /// 格式化获取到的mac地址 /// 获取到的mac地址 public static string GetMacAddress(NetworkInterfaceType networkType, OperationalStatus status, Func macAddressFormatHanlder) { string _mac = string.Empty; NetworkInterface[] _networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in _networkInterfaces) { if (adapter.NetworkInterfaceType == networkType) { if (adapter.OperationalStatus != status) continue; _mac = adapter.GetPhysicalAddress().ToString(); if (!String.IsNullOrEmpty(_mac)) break; } } if (macAddressFormatHanlder != null) _mac = macAddressFormatHanlder(_mac); return _mac; } ///  /// 获取读到的第一个mac地址 ///  /// 获取到的mac地址 public static string GetMacAddress(Func macAddressFormatHanlder) { string _mac = string.Empty; NetworkInterface[] _networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in _networkInterfaces) { _mac = adapter.GetPhysicalAddress().ToString(); if (!string.IsNullOrEmpty(_mac)) break; } if (macAddressFormatHanlder != null) _mac = macAddressFormatHanlder(_mac); return _mac; } 

有些项目中出于安全考虑需要获取MAC地址,然后再判断MAC地址是否合法才可以登陆。本文总结的方法希望对大家有所帮助!

以上就是C#实现获取MAC地址的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程