Skip to content

Instantly share code, notes, and snippets.

@mallowigi
Last active July 3, 2016 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mallowigi/813e04080d2ced526f0fe1dd6872a0c1 to your computer and use it in GitHub Desktop.
Save mallowigi/813e04080d2ced526f0fe1dd6872a0c1 to your computer and use it in GitHub Desktop.
Ipaddr.rb
require 'ipaddr'
# Builtin
def ip_to_int32(ip)
x = IPAddr.new(ip).to_i
end
def ip_to_int32(ip)
ip.split( '.' ).reduce( 0 ) { |total, p| total * 256 + p.to_i }
end
# Using format
def ip_to_int32(ip)
("%02x%02x%02x%02x" % ip.split('.')).to_i(16)
end
# Using binary
def ip_to_int32(ip)
ip.split(".").inject(0) { |memo, val| (memo << 8) + val.to_i }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment