MAC Address Generator — C# source
Generate random EUI-48 MAC addresses with a chosen separator, optional OUI prefix, uppercase formatting, and a locally-administered flag. Runs entirely in your browser with crypto-grade randomness.
This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.
// mac-address-generator — random EUI-48 MAC address generator. C# (.NET 8)
// port (canonical TS: src/lib/mac-generator.ts; Go twin:
// cli/mac-address-generator). The default rng draws from
// RandomNumberGenerator (the crypto source the TS lib uses); the showcase
// keeps the rng injectable (Func<double> returning [0, 1)) so the demo
// asserts exact MAC strings.
using System;
using System.Linq;
using System.Security.Cryptography;
record MacOptions(
string? Separator = null, // null -> ":"; "" concatenates
bool Uppercase = false,
string? Oui = null, // 6 hex digits (separators tolerated)
bool LocallyAdministered = false, // force U/L bit (0x02) of the first octet
Func<double>? Rng = null); // null -> crypto draw in [0, 1)
static class MacGenerator
{
static readonly Func<double> DefaultRng = () =>
RandomNumberGenerator.GetInt32(1 << 30) / (double)(1 << 30);
// Strip non-hex chars, require exactly 6 digits, parse the 3 OUI octets.
static int[] ParseOui(string oui)
{
var clean = new string(oui.Where(Uri.IsHexDigit).ToArray());
if (clean.Length != 6)
throw new ArgumentException($"OUI must be 6 hex digits, got \"{oui}\"");
return new[] { Convert.ToInt32(clean[0..2], 16), Convert.ToInt32(clean[2..4], 16), Convert.ToInt32(clean[4..6], 16) };
}
// Build a random EUI-48 MAC: 3 OUI octets (given or random) + 3 random,
// U/L bit forced when asked, joined as %02x with the separator.
public static string Generate(MacOptions? o = null)
{
o ??= new MacOptions();
var rng = o.Rng ?? DefaultRng;
var oct = o.Oui is { Length: > 0 }
? ParseOui(o.Oui)
: Enumerable.Range(0, 3).Select(_ => (int)(rng() * 256)).ToArray();
oct = oct.Concat(Enumerable.Range(0, 3).Select(_ => (int)(rng() * 256))).ToArray();
if (o.LocallyAdministered) oct[0] = (oct[0] & 0xFD) | 0x02;
var mac = string.Join(o.Separator ?? ":", oct.Select(b => b.ToString("x2")));
return o.Uppercase ? mac.ToUpperInvariant() : mac;
}
}
class Demo
{
static void Main()
{
Console.WriteLine(MacGenerator.Generate(new(Rng: () => 0))); // 00:00:00:00:00:00
Console.WriteLine(MacGenerator.Generate(new(Separator: "-"))); // 6 random pairs, dash-joined
Console.WriteLine(MacGenerator.Generate(new(Rng: () => 0.7, Uppercase: true))); // B3:B3:B3:B3:B3:B3
Console.WriteLine(MacGenerator.Generate(new(Rng: () => 0, Oui: "aa-bb-cc"))); // aa:bb:cc:00:00:00
Console.WriteLine(MacGenerator.Generate(new(Rng: () => 0.5, LocallyAdministered: true))); // 82:80:80:80:80:80
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →