在ruby中将ip地址转换为32位整数

我试图找到一种方法将Ruby地址转换为32位整数,用于木偶模板。

这就是我在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 

任何帮助将不胜感激。

 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 

上面的答案稍好一些,因为你的八位字节可能有超过3位数,然后这会破坏。 IE

 "127.0.0.1234" 

但我仍然更喜欢我:D如果这对你很重要,那么你就可以做到

 "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 }