C#获取电脑的网卡地址

使用C#开发Windows应用,需要进行特定网卡绑定的时候我们需要获取电脑本机的网卡地址,本文会介绍几种获取电脑网卡地址的方法。

使用 NetworkInterface

在公共类库中已经有了专门的网卡接口类:NetworkInterface ,该类存在于 System.Net.NetworkInformation 命名空间下,可以获取电脑上的所有网络接口。

using System;
using System.Net.NetworkInformation;

class Program
{
    static void Main()
    {
        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            Console.WriteLine($"MAC地址: {nic.GetPhysicalAddress()}");
        }
    }
}

使用 WMI

WMI,全称为:Windows Management Instrumentation,专门用来查询Windows系统信息,我们需要用到 Win32_NetworkAdapterConfiguration 来查询网卡信息。

using System;
using System.Management;

class Program
{
    static void Main()
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
            if ((bool)mo["IPEnabled"])
            {
                Console.WriteLine($"MAC地址: {mo["MacAddress"]}");
            }
        }
    }
}

使用 ipconfig 命令

除了上述两种方法外,还可以直接调用命令 ipconfig /all ,在输出的字符串中匹配并提取MAC地址。

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/c ipconfig /all";
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;
        process.Start();

        string output = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        var infoAllLine = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        var physicalLine = infoAllLine.Where(x => x.Contains("物理地址") || x.Contains("Physical Address")).ToList();
        foreach (var line in physicalLine)
        {
            Console.WriteLine($"MAC地址: {line.Split(':').Last()}");
        }
    }
}
发布时间:2025-05-14
其他阅读

Winform中设置控件边框

本文将会介绍在Winform中如何设置控件的边框,可应用于Form和Panel等。

查看原文

WPF中切换主题功能

在现代 Windows 系统中,系统提供了亮色主题和暗色主题,Windows 自带的应用程序都已经适配该功能。本文介绍在使用 WPF 构建 Windows 窗口应用时怎么实现主题切换。

查看原文

网页小技巧

分享一些网页开发中实用的UI小技巧,快速完成页面搭建工作。

查看原文

WPF中开启虚拟化提高性能

WPF(Windows Presentation Foundation)是一个强大的框架,它能创建高度响应和美观的桌面应用程序。然而,当处理大量数据时,性能问题可能变得显著。为了解决这些问题,我们可以利用虚拟化来提升WPF应用的性能。

查看原文

WPF使用云母材质

在最新的Windows 11 OS中,微软为流畅设计(Fluent Design)带来了新的云母材质,云母材质一种不透明的动态效果,微软将其作为Windows 11应用窗体的默认材质。

查看原文