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

西华湿地公园

昆明周末好去处。

查看原文

使用C#接入DeepSeek API实现自己的AI助手

过年期间DeepSeek非常火爆,这段时间用着官方的客户端访问,总是会提示“服务器繁忙,请稍后再试。”,本文介绍怎么通过接入DeepSeek的API实现自己的客户端。

查看原文

如何查看系统端口占用

在web开发中,时常会遇到开发的应用无法启动,这种情况一般是由于当前监听端口已经被别的应用先行占用监听了。本文就 Windows 和 Linux 介绍一下查看端口占用程序。

查看原文

记录中文名WPF应用无法启动

今年开春,突然就收到部分用户反馈软件无法启动的问题,沟通后远程查看发现应用刚启动就直接崩溃了,在Windows的事件查看器可以看到应用的崩溃日志,发现是 ucrtbase.dll 模块崩溃,错误代码 0x0000409

查看原文

个人简介

你好,我是猪头少年,是一名定居在云南的软件工程师,主要的开发语言为 C#JavaScript,涉及 ASP.NET CoreWPFAngularUnity 以及 Babylon.js。平时喜欢自驾出游。欢迎大家联系我。

查看原文