获取 MAC 地址 C#

发布于 2024-09-07 14:58:07 字数 554 浏览 4 评论 0原文

我发现这段代码可以获取 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 的内容。

有什么想法吗?

谢谢。

I have found this code to get a MAC address, but it returns a long string and doesn't include ':'.

Is it possible to add in the ':' or split up the string and add it it myself?

here is the code:

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

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

    return macAddresses;
 }

It returns the value of 00E0EE00EE00 whereas I want it to display something like 00:E0:EE:00:EE:00.

Any ideas?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

雾里花 2024-09-14 14:58:08

我正在使用以下代码以您想要的格式访问 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;
        }

i am using following code to access mac address in format you want :

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;
        }
暮光沉寂 2024-09-14 14:58:08

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

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

You can use the BitConverter.ToString() method:

var hex = BitConverter.ToString( nic.GetPhysicalAddress().GetAddressBytes() );
hex.Replace( "-", ":" );
撕心裂肺的伤痛 2024-09-14 14:58:08

您可以使用此代码(使用 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());
}

You can use this code (uses 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());
}
乱了心跳 2024-09-14 14:58:08

使用 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"

Using LINQ just replace

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

with

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

You can also play with ToString parameter, for instance if you like 00:e0:ee:00:ee:00 more than 00:E0:EE:00:EE:00 then you can just pass "x2" instead of "X2".

恋你朝朝暮暮 2024-09-14 14:58:08
   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());
        }
   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());
        }
沫雨熙 2024-09-14 14:58:08
function string GetSplitedMacAddress(string macAddresses)
{
    for (int Idx = 2; Idx <= 15; Idx += 3)
    {
        macAddresses = macAddresses.Insert(Idx, ":");
    }

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

    return macAddresses;
}
酒中人 2024-09-14 14:58:08

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

Use the GetAddressBytes method:

    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("-");
        }
    }
缘字诀 2024-09-14 14:58:08

//MAC地址

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

//MAC Address

var macAddress = NetworkInterface.GetAllNetworkInterfaces();
var getTarget = macAddress[0].GetPhysicalAddress();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文