Home >Backend Development >C++ >How Can I Reliably Obtain a Machine's MAC Address in C# Across Different Platforms?

How Can I Reliably Obtain a Machine's MAC Address in C# Across Different Platforms?

Susan Sarandon
Susan SarandonOriginal
2025-01-17 01:21:10613browse

How Can I Reliably Obtain a Machine's MAC Address in C# Across Different Platforms?

A Cross-Platform Solution for Retrieving MAC Addresses in C#

Getting a machine's MAC address consistently across different operating systems is tricky because of variations in command line outputs and language settings. This article presents a reliable, platform-independent method.

The Reliable Method: Using NetworkInterface

The most dependable approach uses the NetworkInterface class. This works consistently across Windows XP, Vista, 7, and beyond, in both 32-bit and 64-bit environments, regardless of the system's language.

Code Examples

Here are two ways to implement this:

Method 1:

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

Method 2 (More Concise):

<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>

Both methods effectively retrieve the MAC address, making it readily available for use in various applications. The second method adds a check to exclude loopback interfaces.

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

Statement:
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