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@ubuntu-server2:~# cat test.sh
#!/bin/bash
#eth0 address is 10.0.2.15
privip=`ifconfig eth0 | grep "inet addr:" | cut -d : -f 2 | cut -d " " -f 1` ;
echo "Private IP: ${privip}" ;
# Turn it into unsigned 32-bit integer
ipiter=3 ;
for ipoctet in `echo ${privip} | tr . " "` ;
do
ipint=$(( ipint + ( ipoctet * 256 ** ipiter-- ) )) ;
done ;
echo "Private IP int32: ${ipint}" ;
.
root@ubuntu-server2:~# bash test.sh
Private IP: 10.0.2.15
Private IP int32: 167772687
Any help would be greatly appreciated.
require 'ipaddr'
ip = IPAddr.new "10.0.2.15"
ip.to_i # 167772687
'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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With