Home > Backend Development > C++ > How Can I Reliably Retrieve a Machine's MAC Address in C#?

How Can I Reliably Retrieve a Machine's MAC Address in C#?

DDD
Release: 2025-01-17 01:26:08
Original
879 people have browsed it

How Can I Reliably Retrieve a Machine's MAC Address in C#?

Robustly Obtaining a Computer's MAC Address in C#

Getting a machine's MAC address reliably in C# can be tricky due to OS and language inconsistencies. While ipconfig /all might seem like a solution, its output format varies across systems, making it unreliable.

A Dependable Approach

A more robust method leverages the NetworkInterface class in C#. This provides a consistent way to retrieve MAC addresses irrespective of the operating system or language. Here's how:

<code class="language-csharp">var macAddr = 
    (
        from nic in NetworkInterface.GetAllNetworkInterfaces()
        where nic.OperationalStatus == OperationalStatus.Up
        select nic.GetPhysicalAddress().ToString()
    ).FirstOrDefault();</code>
Copy after login

This code retrieves all network interfaces, filters for active ones, and selects their physical addresses (MAC addresses). FirstOrDefault() returns the first MAC address found.

Alternative Implementation (More Explicit)

A slightly more detailed approach offers the same result:

<code class="language-csharp">string firstMacAddress = NetworkInterface
    .GetAllNetworkInterfaces()
    .Where(nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
    .Select(nic => nic.GetPhysicalAddress().ToString())
    .FirstOrDefault();</code>
Copy after login

This explicitly excludes inactive and loopback interfaces, ensuring only valid MAC addresses are considered.

The above is the detailed content of How Can I Reliably Retrieve a Machine's MAC Address in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template