c#获取本机的MAC地址(附源码)

在前一次的项目中,突然用到了这个获取本机的MAC地址,然后就研究了一下,记录下来,防止以后再用到,

使用winfrom做的,界面一个button,一个textBox,点了button以后给textBox赋值显示mac地址

附上源码

cs 复制代码
 private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string macAddress = GetMacAddress();
                if (!string.IsNullOrEmpty(macAddress))
                {
                    textBox1.Text = macAddress;
                }
                else
                {
                    MessageBox.Show("未能获取到MAC地址。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取MAC地址时出现错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetMacAddress()
        {
            try
            {
                string macAddress = string.Empty;
                foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    /// 仅考虑以太网的网络接口
                    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nic.OperationalStatus == OperationalStatus.Up)
                    {
                        // 获取网络接口的MAC地址
                        macAddress = nic.GetPhysicalAddress().ToString();
                        // 将连续的十六进制数格式化为带冒号分隔符的形式
                        macAddress = FormatMacAddress(macAddress);
                        if (!string.IsNullOrEmpty(macAddress))
                            break;
                    }
                }
                return macAddress;
            }
            catch (UnauthorizedAccessException)
            {
                throw new Exception("没有足够的权限来访问网络接口信息,请以管理员身份运行程序。");
            }
            catch (Exception ex)
            {
                throw new Exception($"获取MAC地址时出现错误:{ex.Message}");
            }
        }
        // 使用正则表达式将连续的十六进制数格式化为带冒号分隔符的形式
        private string FormatMacAddress(string macAddress)
        {
            
            return Regex.Replace(macAddress, @"(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})", "$1:$2:$3:$4:$5:$6");
        }
相关推荐
helloworldandy15 分钟前
高性能图像处理库
开发语言·c++·算法
2401_8365631816 分钟前
C++中的枚举类高级用法
开发语言·c++·算法
chao18984427 分钟前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
EmbedLinX44 分钟前
C++ 面向对象
开发语言·c++
weixin_445402301 小时前
C++中的命令模式变体
开发语言·c++·算法
Hgfdsaqwr1 小时前
实时控制系统优化
开发语言·c++·算法
2301_821369611 小时前
嵌入式实时C++编程
开发语言·c++·算法
sjjhd6521 小时前
多核并行计算优化
开发语言·c++·算法
一起养小猫2 小时前
Flutter for OpenHarmony 实战 表单处理与验证完整指南
android·开发语言·前端·javascript·flutter·harmonyos
leiming62 小时前
FreeRTOS 的任务与 Linux
java·开发语言