栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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地址是否合法才可以登陆。本文总结的方法希望对大家有所帮助!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/126307.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号