Skip to content

Instantly share code, notes, and snippets.

@jimsynz
Created October 21, 2011 01:50
Show Gist options
  • Save jimsynz/1302917 to your computer and use it in GitHub Desktop.
Save jimsynz/1302917 to your computer and use it in GitHub Desktop.
require 'ipaddr_extensions'
def generate_unique_local(mac, subnet_id = 0, locally_assigned=true)
now = Time.now
ntp_time = (now.to_i << 32) + now.nsec
system_id = '::/64'.to_ip.eui_64(mac).to_i
integer_key = (ntp_time << 64) + system_id
key = []
16.times do |i|
key << ((integer_key >> (i*8)) & 0xff)
end
global_id = Digest::SHA1.digest(key.pack('C' * 16))[-8..-1].unpack('Q').first & 0xffffffffff
prefix = (126 << 121) + # 0xfc00
((locally_assigned ? 1 : 0) << 120) + # L = 1 || 0
(global_id << 80) +
((subnet_id & 0xffff) << 64) # 16 bit subnet_id
prefix.to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment