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.
The answer above is slightly better, because you could have more than 3 digits in your octet and then this will break. IE
But I still like mine better :D Also if that is important to you, then you can just do