C#获取电脑的网卡地址

发布时间:2025-05-14

使用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()}");
        }
    }
}
其他阅读

网页小技巧

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

查看原文

WPF中创建一个矩形圆角动画

WPF 中内置了好几种动画,大多数场景可以坐到开箱即用,不过并没有内置 CornerRadiusAnimation ,本文将会介绍怎么实现一个 CornerRadiusAnimation 动画,实现 BorderCornerRadius 属性动画效果。

查看原文

WPF中切换主题功能

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

查看原文

命令行打包.net项目

.net 日常开发中,我们接触最多的就是 Visual Studio ,它是微软为了 .net 平台专门打造的 IDE (集成开发环境),为整个 .net 平台开发带来了无与伦比的图形化体验,但是有时候,我们也会遇到需要通过命令行来生成 .net 项目的情况,本文会介绍几种命令行打包的姿势。

查看原文

Nginx重定向HTTP到HTTPS

HTTP协议以纯文本形式进行数据的交互,数据明文传输,容易被监听,窃取和伪造,HTTPS在HTTP的基础上,使用了TLS/SSL对通信过程进行加密,数据得到了有效的保护,就算被拦截到也无法获取信息,更没法实施中间人攻击。本文将会介绍如何在Nginx中配置HTTP重定向到HTTPS。

查看原文