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