我正在寻找 C# 中生成随机 MAC 号的方法。谷歌在那个方面相当薄弱。
多谢
解决方案:
在 Yahia 的帮助下,我能够编写以下解决方案。再次感谢!
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)");
}
}