I am looking for a method in C# which generates a random MAC number. Google is pretty thin on that one.
Thx a lot
SOLUTION:
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)");
}
}
There is no such method in the .NET framework...
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...