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

Fetch发送请求

fetch 是 javascript 中一个新的 api,用于访问和控制 HTTP 的请求和响应等,不再需要使用传统的 XMLHttoRequest

查看原文

使用正则表达式来判断邮箱

在开发中,很多地方都需要用户输入邮箱,用户注册,登录需要邮箱,订阅消息需要邮箱,为了防止被恶意使用,一般都会使用正则表达式来判断输入是否符合邮箱规范

查看原文

网页上通过超链接直接打开PC应用

有时候我们会发现有些网页可以直接打开本地应用,比如在百度网盘网页版下载文件时,会自动打开本地的百度网盘软件。Visual Studio Code打开浏览器认证后也会转到本地引用,Unity官网打开本地的Unity Hub应用进行Unity的下载和更新等。

查看原文

WPF中切换主题功能

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

查看原文

JSON是什么

在现代化 Web 应用开发中,广泛使用一种名为 JSON 的数据交换格式。JSON 是一种轻量级数据交换格式,在不同系统之间提供标准且高效的数据交换。

查看原文