Skip to content

Instantly share code, notes, and snippets.

@Deraen
Last active August 10, 2016 10:44
Show Gist options
  • Save Deraen/589e94287dc13ffcda3451d7bf155eae to your computer and use it in GitHub Desktop.
Save Deraen/589e94287dc13ffcda3451d7bf155eae to your computer and use it in GitHub Desktop.
Use project-name to generate IP's for vagrant boxes

Why

  • Static IPs with Vagrant clash easily with other projects
  • Dynamic IPs require using port forwards -> port forwards clash with local apps and other projects
  • Solution: Provide static IP which are calculated from project name, and then use vagrant-hostupdater to add name -> IP to hosts files for easy use
  • Uses 20 first bits from MD5 hash of the name to build IPv4 in Class B private network (smaller addres space than Class A, but rarely used)
require 'digest'
require 'ipaddr'
def project_ip(project_name)
mask = ((1 << 21) - 1)
low = (172 << 24) | (16 << 16)
high = Digest::MD5.hexdigest(project_name).to_i(16) & mask
return IPAddr.new(low | high, Socket::AF_INET).to_s
end
# project_ip("foobar")
# => "172.18.198.63"
# project_ip("projectproject")
# => "172.17.169.109"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment