Skip to content

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

# mac-address-generator — random EUI-48 MAC address generator. Ruby port
# (canonical TS: src/lib/mac-generator.ts; Go twin: cli/mac-address-generator).
# The default rng draws from SecureRandom (the crypto source the TS lib uses);
# the showcase keeps the rng injectable (a Proc returning [0, 1)) so the demo
# asserts exact MAC strings.
require 'securerandom'

module MacGenerator
  module_function

  # Strip non-hex chars, require exactly 6 digits, parse the 3 OUI octets.
  def parse_oui(oui)
    clean = oui.gsub(/[^0-9a-fA-F]/, '')
    raise ArgumentError, "OUI must be 6 hex digits, got \"#{oui}\"" unless clean.length == 6
    [0, 2, 4].map { |i| clean[i, 2].to_i(16) }
  end

  # 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.
  def generate_mac(separator: ':', uppercase: false, oui: nil, locally_administered: false,
                   rng: -> { SecureRandom.random_number })
    # TS `if (opts.oui)` truthiness: nil and "" both take the random path.
    oct = oui && !oui.empty? ? parse_oui(oui) : Array.new(3) { (rng.call * 256).to_i }
    oct += Array.new(3) { (rng.call * 256).to_i }
    oct[0] = (oct[0] & 0xFD) | 0x02 if locally_administered
    mac = oct.map { |o| format('%02x', o) }.join(separator)
    uppercase ? mac.upcase : mac
  end
end

if __FILE__ == $PROGRAM_NAME
  puts MacGenerator.generate_mac(rng: -> { 0 })                              # 00:00:00:00:00:00
  puts MacGenerator.generate_mac(separator: '-')                            # 6 random pairs, dash-joined
  puts MacGenerator.generate_mac(rng: -> { 0.7 }, uppercase: true)          # B3:B3:B3:B3:B3:B3
  puts MacGenerator.generate_mac(rng: -> { 0 }, oui: 'aa-bb-cc')            # aa:bb:cc:00:00:00
  puts MacGenerator.generate_mac(rng: -> { 0.5 }, locally_administered: true) # 82:80:80:80:80:80
end

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 →