I am trying to find a way to convert a ip address to a 32 bit integer in Ruby for a puppet template.
This is how I did the conversion in bash.
root@u
'10.0.2.15'.split('.').inject(0) {|total,value| (total << 8 ) + value.to_i}
#=> 167772687
The answer above is slightly better, because you could have more than 3 digits in your octet and then this will break. IE
"127.0.0.1234"
But I still like mine better :D Also if that is important to you, then you can just do
"127.0.0.1".split('.').inject(0) {|total,value| raise "Invalid IP" if value.to_i < 0 || value.to_i > 255; (total << 8 ) + value.to_i }
require 'ipaddr'
ip = IPAddr.new "10.0.2.15"
ip.to_i # 167772687