Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert ip address to 32 bit integer in ruby

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.

like image 403
Chandler Cord Avatar asked Nov 06 '12 05:11

Chandler Cord


2 Answers

require 'ipaddr'
ip = IPAddr.new "10.0.2.15"
ip.to_i                      # 167772687  
like image 91
halfelf Avatar answered Nov 12 '22 15:11

halfelf


'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 }
like image 4
earlonrails Avatar answered Nov 12 '22 15:11

earlonrails