生成随机mac地址 [英] Generate a random mac address

查看:52
本文介绍了生成随机mac地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 C# 中寻找一种生成随机 MAC 数的方法.谷歌在这方面做得很差.

I am looking for a method in C# which generates a random MAC number. Google is pretty thin on that one.

非常感谢

解决方案:

在 Yahia 的帮助下,我能够编写以下解决方案.再次感谢!

With the help of Yahia I was able to code the following solution. Thx again!

public static string GenerateMACAddress()
    {
        var sBuilder = new StringBuilder();
        var r = new Random();
        int number;
        byte b;
        for (int i = 0; i < 6; i++)
        {
            number = r.Next(0, 255);
            b = Convert.ToByte(number);
            if (i == 0)
            {
                b = setBit(b, 6); //--> set locally administered
                b = unsetBit(b, 7); // --> set unicast 
            }
            sBuilder.Append(number.ToString("X2"));
        }
        return sBuilder.ToString().ToUpper();
    }

    private static byte setBit(byte b, int BitNumber)
    {
        if (BitNumber < 8 && BitNumber > -1)
        {
            return (byte)(b | (byte)(0x01 << BitNumber));
        }
        else
        {
            throw new InvalidOperationException(
            "Der Wert für BitNumber " + BitNumber.ToString() + " war nicht im zulässigen Bereich! (BitNumber = (min)0 - (max)7)");
        }
    }

    private static byte unsetBit(byte b, int BitNumber)
    {
        if (BitNumber < 8 && BitNumber > -1)
        {
            return (byte)(b | (byte)(0x00 << BitNumber));
        }
        else
        {
            throw new InvalidOperationException(
            "Der Wert für BitNumber " + BitNumber.ToString() + " war nicht im zulässigen Bereich! (BitNumber = (min)0 - (max)7)");
        }
    }

推荐答案

.NET框架中没有这样的方法...

There is no such method in the .NET framework...

您需要自己编写一个 - 阅读格式说明,使用随机生成器 获取 0 到 255 之间的 6 个随机数,设置 2 个相关位(全局唯一/本地管理)根据需要,然后转换数字到十六进制(即 X2,每个数字 2 位,左填充 0)和 : 作为分隔符...

You will need to write one yourself - read the format description, use a random generator to get 6 random numbers between 0 and 255, setup the 2 relevant bits (for globally unique/locally administered) as need be and then transform the number to hex (i.e. X2, 2 digits per number, left padded with 0) and join these together with : as delimiter...

这篇关于生成随机mac地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆