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

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

Patricia Arquette
Release: 2025-01-17 01:07:08
Original
566 people have browsed it

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

Precisely Obtaining a Machine's MAC Address in C#

Many applications require retrieving a computer's MAC address across different operating systems. This can be difficult because of variations in OS structure and language settings. Simple methods, like parsing the output of "ipconfig /all," are unreliable due to inconsistent formatting.

For a robust solution, consider these approaches:

(1) Improved Method

This code uses LINQ for efficient MAC address extraction:

<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

(2) Enhanced LINQ Query

This refined LINQ expression offers improved accuracy:

<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

These methods are designed for cross-platform compatibility and consistent, reliable MAC address retrieval.

The above is the detailed content of How Can I Reliably Get 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template