开发者

Getting MAC Address C#

开发者 https://www.devze.com 2023-01-05 04:23 出处:网络
I have found this code to get a MAC address, but it returns a long string and doesn\'t include \':\'.

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 == Opera开发者_StackOverflow中文版tionalStatus.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.


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;
        }


You can use the BitConverter.ToString() method:

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


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


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".


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


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

    return macAddresses;
}


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


//MAC Address

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

精彩评论

暂无评论...
验证码 换一张
取 消