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

Linux中查看,添加,修改,删除用户和用户组

将用户分组是Linux系统中对用户进行管理及控制访问权限的一种手段。某个用户都属于某个用户组;一个组中可以有多个用户,一个用户也可以属于不同的组。当一个用户同时是多个组中的成员时,登录时所属的为默认组,而其他组称为附加组。本文将会介绍在 Linux 中查看,添加,修改,删除用户和用户组,注意:权限管理非常重要,可能一不小心就导致系统无法登录,请谨慎操作

查看原文

WPF托盘运行

本文介绍如何将WPF应用最小化到托盘,窗口关闭后进程仍然运行的方法。

查看原文

IIS 设置跨域问题

之前说过nginx设置跨域,今天记录以下IIS设置跨域

查看原文

使用表达式树来提高反射的性能

反射是C#中一种常用的技术,反射提供了动态创建和访问对象的基础,但是反射在带来了极强的灵活性的同时,也带了极大的性能损耗,本文就介绍通过表达式树来提高反射过程中的性能。

查看原文

TypeScript中的数组操作

我们在编码时,总会用到数组/列表这种类型,用于在单个对象中存储多个内容。在 TypeScript 中,也已经内置了该类型,方便我们来使用。

查看原文