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
其他阅读

新版本.Net关于Process.Start的问题

.Net 开发中,试用 Process.Start() 来启动一个新进程,当我们传入的是具体文件或者链接的时候,系统也会根据默认打开方式打开对应的进程。但是在新版本的 .Net 中,试用 Process.Start() 来打开文件或者链接的时候,会抛出 System.ComponentModel.Win32Exception 的错误,提示系统找不到指定的文件。

查看原文

Js使用原型链对对象进行扩展

在C#的扩展方法中,我们了解到了一种不需要修改源对象定义即可为对象添加新的行为的方法,在JavaScript中,我们通过原型链也可以实现类似的效果,为对象添加新的行为。需要一定的Js原型链基础。

查看原文

Blazor文件上传解决方案

Blazor 是由 Asp.Net Core 团队推出的一个Web前端SPA解决方案,其中包括了使用 WebAssembly 的 Blazor Wasm 和使用 SignalR 进行实时交互的 Blazor server。本篇文章中使用的是 Blazor Wasm 方案来验证上传文件的操作。

查看原文

Linux查看版本信息

介绍几种查看 Linux 版本的方法,方便在使用 Linux 时快速定位自己的系统版本,使用合适的工具。

查看原文

WPF打包成单文件

在开发WPF程序时,有时我们需要把整个软件打包成一个文件,这样可以方便分发,本文将会介绍怎么把WPF打包成单文件形式。

查看原文