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