Как получить Bluetooth-адрес Mac с локального компьютера?

StackOverflow https://stackoverflow.com/questions/1819971

  •  10-07-2019
  •  | 
  •  

Вопрос

Я хочу получить MAC-адрес устройства Bluetooth на компьютере, на котором запущено мое приложение.

Я пробовал следующее:

private void GetMacAddress()
{
     string macAddresses = "";
     foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
     {
          if (nic.OperationalStatus == OperationalStatus.Up)
          {
               macAddresses += nic.GetPhysicalAddress().ToString();
               Console.WriteLine(macAddresses);
          }
     }
}

Но вывод не совпадает с 'ipconfig / all' в командной строке. Он не печатает мой macot адрес blueotths. Какие-нибудь решения?

Я готов проанализировать вывод, полученный из 'ipconfig / all', но как мне получить вывод в виде строки?

Это было полезно?

Решение

Вы можете использовать WMI для получения результатов. При этом ссылка на решение WMI, которое проходит через сетевые устройства.

Я публикую здесь код на случай, если веб-сайт не работает, но вся заслуга принадлежит первоначальному автору, PsychoCoder. Используйте WMI для получения MAC-адреса в C #

И код:

//Namespace reference
using System.Management;

/// <summary>
/// Returns MAC Address from first Network Card in Computer
/// </summary>
/// <returns>MAC Address in string format</returns>
public string FindMACAddress()
{
    //create out management class object using the
    //Win32_NetworkAdapterConfiguration class to get the attributes
    //af the network adapter
    ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
    //create our ManagementObjectCollection to get the attributes with
    ManagementObjectCollection objCol = mgmt.GetInstances();
    string address = String.Empty;
    //My modification to the code
    var description = String.Empty;
    //loop through all the objects we find
    foreach (ManagementObject obj in objCol)
    {
        if (address == String.Empty)  // only return MAC Address from first card
        {
            //grab the value from the first network adapter we find
            //you can change the string to an array and get all
            //network adapters found as well
            if ((bool)obj["IPEnabled"] == true)
            {
                address = obj["MacAddress"].ToString();
                description = obj["Description"].ToString();
            }
        }
       //dispose of our object
       obj.Dispose();
    }
    //replace the ":" with an empty space, this could also
    //be removed if you wish
    address = address.Replace(":", "");
    //return the mac address
    return address;
}

Обязательно включите ссылку на System.Management. Чтобы получить имя сетевого устройства, вы можете использовать obj [" Description "]. ToString ();

Вы также можете взглянуть на MSDN относительно WMI, в частности на Класс Win32_NetworkAdapterConfiguration

Надеюсь, это поможет.

Другие советы

public static PhysicalAddress GetBTMacAddress()  {

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {

        // Only consider Bluetooth network interfaces
        if (nic.NetworkInterfaceType != NetworkInterfaceType.FastEthernetFx && 
            nic.NetworkInterfaceType != NetworkInterfaceType.Wireless80211){

            return nic.GetPhysicalAddress();
        }
    }
    return null;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top