获取MAC地址C#

时间:2010-07-01 11:19:58

标签: c# mac-address

我发现此代码获取MAC地址,但它返回一个长字符串,但不包含':'。

是否可以添加':'或拆分字符串并自行添加?

这是代码:

private object GetMACAddress()
{
    string macAddresses = "";

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            macAddresses += nic.GetPhysicalAddress().ToString();
            break;
        }
    }

    return macAddresses;
 }

它返回值00E0EE00EE00,而我希望它显示类似00:E0:EE:00:EE:00。

有什么想法吗?

感谢。

8 个答案:

答案 0 :(得分:10)

我使用以下代码以您想要的格式访问mac地址:

public string GetSystemMACID()
        {
            string systemName = System.Windows.Forms.SystemInformation.ComputerName;
            try
            {
                ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
                ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
                ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
                ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

                foreach (ManagementObject theCurrentObject in theCollectionOfResults)
                {
                    if (theCurrentObject["MACAddress"] != null)
                    {
                        string macAdd = theCurrentObject["MACAddress"].ToString();
                        return macAdd.Replace(':', '-');
                    }
                }
            }
            catch (ManagementException e)
            {
                           }
            catch (System.UnauthorizedAccessException e)
            {

            }
            return string.Empty;
        }

答案 1 :(得分:8)

您可以使用BitConverter.ToString()方法:

var hex = BitConverter.ToString( nic.GetPhysicalAddress().GetAddressBytes() );
hex.Replace( "-", ":" );

答案 2 :(得分:3)

使用LINQ替换

macAddresses += nic.GetPhysicalAddress().ToString();
// Produces "00E0EE00EE00"

macAddresses += String.Join(":", nic.GetPhysicalAddress()
                                    .GetAddressBytes()
                                    .Select(b => b.ToString("X2"))
                                    .ToArray());
// Produces "00:E0:EE:00:EE:00"

您还可以使用ToString参数进行游戏,例如,如果您希望00:e0:ee:00:ee:00超过00:E0:EE:00:EE:00,则可以通过"x2"代替"X2"

答案 3 :(得分:2)

您可以使用此代码(使用LINQ):

using System.Linq;
using System.Net;
using System.Net.NetworkInformation;

// ....

private static string GetMACAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
            return AddressBytesToString(nic.GetPhysicalAddress().GetAddressBytes());
    }

    return string.Empty;
}

private static string AddressBytesToString(byte[] addressBytes)
{
    return string.Join(":", (from b in addressBytes
                             select b.ToString("X2")).ToArray());
}

答案 4 :(得分:1)

   private string GetUserMacAddress()
        {
            var networkInterface = NetworkInterface.GetAllNetworkInterfaces()
                .FirstOrDefault(q => q.OperationalStatus == OperationalStatus.Up);

            if (networkInterface == null)
            {
                return string.Empty;
            }

            return BitConverter.ToString(networkInterface.GetPhysicalAddress().GetAddressBytes());
        }

答案 5 :(得分:0)

使用GetAddressBytes方法:

    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("-");
        }
    }

答案 6 :(得分:0)

function string GetSplitedMacAddress(string macAddresses)
{
    for (int Idx = 2; Idx <= 15; Idx += 3)
    {
        macAddresses = macAddresses.Insert(Idx, ":");
    }

    return macAddresses;
}

答案 7 :(得分:0)

// MAC地址

var macAddress = NetworkInterface.GetAllNetworkInterfaces();
var getTarget = macAddress[0].GetPhysicalAddress();