来自字符串的Mac地址格式

时间:2012-12-08 06:12:05

标签: c#

    NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();

    foreach (NetworkInterface item in arr)
    {
        PhysicalAddress mac = item.GetPhysicalAddress();
    }

它返回值00E0EE00EE00,而我希望它显示类似00:E0:EE:00:EE:00但我需要使用.Net 4

任何想法?

5 个答案:

答案 0 :(得分:5)

您可以使用String.Insert字符串类方法添加:

string macAddStr = "00E0EE00EE00";
string macAddStrNew = macAddStr;
int insertedCount = 0;
for(int i = 2; i < macAddStr.Length; i=i+2)  
   macAddStrNew = macAddStrNew.Insert(i+insertedCount++, ":");

//macAddStrNew will have address 00:E0:EE:00:EE:00

答案 1 :(得分:3)

我知道这已经回答了一段时间,但我只是想澄清一下,首选的解决方案通常是为PhysicalAddress类创建一个可重用的扩展方法。 由于它是一个简单的数据类,并且很可能不会改变,因此出于可重用性的原因这更好。 我将使用洛伦佐的例子,因为我最喜欢它,但你可以使用适合你的常规。

public static class PhysicalAddressExtensions
{
    public static string ToString(this PhysicalAddress address, string separator)
    {
        return string.Join(separator, address.GetAddressBytes()
                                             .Select(x => x.ToString("X2")))
    }
}

现在你可以像现在这样使用扩展方法:

NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface item in arr)
{
    PhysicalAddress mac = item.GetPhysicalAddress();
    string stringFormatMac = mac.ToString(":");
}

请记住,PhysicalAddress.Parse仅接受RAW十六进制或短划线分隔值,以防您想要将其解析回对象。因此,在解析之前剥离分隔符很重要。

答案 2 :(得分:1)

您可以这样做:

    string macAddr = "AAEEBBCCDDFF";
    var splitMac = SplitStringInChunks(macAddr);

    static string SplitStringInChunks(string str)
    {
        for (int i = 2; i < str.Length; i += 3)
             str =  str.Insert(i, ":");
        return str;
    }

答案 3 :(得分:0)

如果需要,可以使用string.Join和Linq .Select():

NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface item in arr)
{
    PhysicalAddress mac = item.GetPhysicalAddress();
    string stringFormatMac = string.Join(":", mac.GetAddressBytes().Select(varByte => varByte.ToString("X2")));
}

希望它有所帮助。

答案 4 :(得分:0)

验证mac并将其格式化为XX:XX:XX:XX:XX:XX格式的方法。

如果无效,则返回null

public string FormatMACAddress(string MacAddress)
{
    if (string.IsNullOrEmpty(MacAddress)) return null;

    MacAddress = MacAddress.ToUpper()
                           .Replace(" ","")
                           .Replace("-", ":") //'AA-BB-CC-11-22-33', 'AA:BB:CC:11:22:33' [17 Chars]
                           .Trim();

    if (!MacAddress.Contains(':') && MacAddress.Length == 12) //'AABBCC112233' [12 Chars]
    {
        for (int i = 2; i < MacAddress.Length; i += 3) MacAddress = MacAddress.Insert(i, ":");
    }

    if (MacAddress.Length != 17) return null; //'AA:BB:CC:11:22:33' [17 Chars]
    if (MacAddress.Count(c => c == ':') != 5) return null;

    //Hex check here, '0-9A-F' and ':'

    return MacAddress;
}

我还没有测试过,但是应该可行。要添加的另一项检查是检查所有字符是否为十六进制值0-9A-F:

相关问题