title: Generate a random mac address
body: <p>I am looking for a method in C# which generates a random MAC number. Google is pretty thin on that one. </p>
  
  <p>Thx a lot</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>With the help of Yahia I was able to code the following solution. Thx again!</p>
  
  <pre><code>public static string GenerateMACAddress()
      {
          var sBuilder = new StringBuilder();
          var r = new Random();
          int number;
          byte b;
          for (int i = 0; i &lt; 6; i++)
          {
              number = r.Next(0, 255);
              b = Convert.ToByte(number);
              if (i == 0)
              {
                  b = setBit(b, 6); //--&gt; set locally administered
                  b = unsetBit(b, 7); // --&gt; set unicast 
              }
              sBuilder.Append(number.ToString("X2"));
          }
          return sBuilder.ToString().ToUpper();
      }
  
      private static byte setBit(byte b, int BitNumber)
      {
          if (BitNumber &lt; 8 &amp;&amp; BitNumber &gt; -1)
          {
              return (byte)(b | (byte)(0x01 &lt;&lt; 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 &lt; 8 &amp;&amp; BitNumber &gt; -1)
          {
              return (byte)(b | (byte)(0x00 &lt;&lt; BitNumber));
          }
          else
          {
              throw new InvalidOperationException(
              "Der Wert für BitNumber " + BitNumber.ToString() + " war nicht im zulässigen Bereich! (BitNumber = (min)0 - (max)7)");
          }
      }
  </code></pre>