Skip to content

MAC Address Generator — TypeScript 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 TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure random MAC address generator (EUI-48). Zero deps; injectable RNG for
// deterministic tests. The unit-test surface for the MAC Address Generator.

export interface MacOptions {
  separator?: ':' | '-' | '.' | '';
  uppercase?: boolean;
  oui?: string; // optional 6-hex-digit OUI prefix (separators tolerated)
  locallyAdministered?: boolean; // set the U/L bit (0x02) of the first octet
  rng?: () => number; // [0, 1)
}

function defaultRng(): number {
  return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
}

function hex(n: number): string {
  return n.toString(16).padStart(2, '0');
}

export function generateMac(opts: MacOptions = {}): string {
  const rng = opts.rng ?? defaultRng;
  const sep = opts.separator ?? ':';
  const octets: number[] = [];

  if (opts.oui) {
    const clean = opts.oui.replace(/[^0-9a-fA-F]/g, '');
    if (clean.length !== 6) throw new Error(`OUI must be 6 hex digits, got "${opts.oui}"`);
    octets.push(
      parseInt(clean.slice(0, 2), 16),
      parseInt(clean.slice(2, 4), 16),
      parseInt(clean.slice(4, 6), 16),
    );
  } else {
    octets.push(Math.floor(rng() * 256), Math.floor(rng() * 256), Math.floor(rng() * 256));
  }
  octets.push(Math.floor(rng() * 256), Math.floor(rng() * 256), Math.floor(rng() * 256));

  if (opts.locallyAdministered) {
    octets[0] = (octets[0] & 0b11111101) | 0b00000010; // set U/L bit, clear multicast
  }

  let mac = octets.map(hex).join(sep);
  if (opts.uppercase) mac = mac.toUpperCase();
  return mac;
}

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 →