Module: Racket::L2::Misc

Defined in:
lib/racket/l2/misc.rb

Overview

Miscelaneous L2 helper methods

Class Method Summary collapse

Class Method Details

.long2mac(long, len = 6) ⇒ Object

given a long representing a MAC address print it out in human readable form of a given length, defaulting to 6 (ethernet)



56
57
58
# File 'lib/racket/l2/misc.rb', line 56

def Misc.long2mac(long, len=6)
  long.to_s(16).rjust(len*2, '0').unpack("a2"*len).join(":")
end

.mac2long(addr) ⇒ Object

given a MAC address, return the long representation



45
46
47
48
49
50
51
# File 'lib/racket/l2/misc.rb', line 45

def Misc.mac2long(addr)
  long = 0
  addr.split(':').map { |s| s.to_i(16) }.each do |o|
    long = (long << 8) ^ o
  end
  long
end

.mac2string(mac) ⇒ Object

given a MAC address, return the string representation



40
41
42
# File 'lib/racket/l2/misc.rb', line 40

def Misc.mac2string(mac)
  mac.split(":").map { |i| i.hex.chr }.join
end

.randommac(len = 6) ⇒ Object

Return a random MAC, defaults to 6 bytes (ethernet)



61
62
63
# File 'lib/racket/l2/misc.rb', line 61

def Misc.randommac(len=6)
  long2mac(rand(2**(8*len)), len)
end

.string2mac(string) ⇒ Object

given a string representing a MAC address, return the human readable form



35
36
37
# File 'lib/racket/l2/misc.rb', line 35

def Misc.string2mac(string)
  string.unpack("C*").map { |i| i.to_s(16).ljust(2,"0") }.join(":")
end