Fast replacement for Win32_NetworkAdapter WMI class for getting MAC address of local computer

前端 未结 2 763
刺人心
刺人心 2021-01-03 08:29

TL;DR version of this question: WMI Win32_NetworkAdapter class contains information I need, but is too slow. What\'s a faster method of getting information for the MACAddre

2条回答
  •  死守一世寂寞
    2021-01-03 09:09

    You should be able to get everything you need from the System.Net namespace. For example, the following sample is lifted from MSDN and does what you asked for in the original version of the question. It displays the physical addresses of all interfaces on the local computer.

    public static void ShowNetworkInterfaces()
    {
        IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        Console.WriteLine("Interface information for {0}.{1}     ",
                computerProperties.HostName, computerProperties.DomainName);
        if (nics == null || nics.Length < 1)
        {
            Console.WriteLine("  No network interfaces found.");
            return;
        }
    
        Console.WriteLine("  Number of interfaces .................... : {0}", nics.Length);
        foreach (NetworkInterface adapter in nics)
        {
            IPInterfaceProperties properties = adapter.GetIPProperties(); //  .GetIPInterfaceProperties();
            Console.WriteLine();
            Console.WriteLine(adapter.Description);
            Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
            Console.WriteLine("  Interface type .......................... : {0}", adapter.NetworkInterfaceType);
            Console.Write("  Physical address ........................ : ");
            PhysicalAddress address = adapter.GetPhysicalAddress();
            byte[] bytes = address.GetAddressBytes();
            for(int i = 0; i< bytes.Length; i++)
            {
                // Display the physical address in hexadecimal.
                Console.Write("{0}", bytes[i].ToString("X2"));
                // Insert a hyphen after each byte, unless we are at the end of the 
                // address.
                if (i != bytes.Length -1)
                {
                     Console.Write("-");
                }
            }
            Console.WriteLine();
        }
    }
    

提交回复
热议问题