Reliable method to get machine's MAC address in C#

Chase picture Chase · May 12, 2009 · Viewed 218.6k times · Source

I need a way to get a machine's MAC address regardless of the OS it is running using C#. Application will need to work on XP/Vista/Win7 32 and 64 bit as well as on those OSs but with a foreign language default. Many of the C# commands and OS queries don't work across OS. Any ideas? I have been scraping the output of "ipconfig /all" but this is terribly unreliable as the output format differs on every machine.

Thanks

Answer

Mohammed A. Fadil picture Mohammed A. Fadil · Oct 5, 2011

Cleaner solution

var macAddr = 
    (
        from nic in NetworkInterface.GetAllNetworkInterfaces()
        where nic.OperationalStatus == OperationalStatus.Up
        select nic.GetPhysicalAddress().ToString()
    ).FirstOrDefault();

Or:

String firstMacAddress = NetworkInterface
    .GetAllNetworkInterfaces()
    .Where( nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback )
    .Select( nic => nic.GetPhysicalAddress().ToString() )
    .FirstOrDefault();