在Ruby中将IP地址转换为32位整数

11

我正在尝试找到一种在Ruby中将IP地址转换为32位整数的方法,以用于puppet模板。

以下是我在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

非常感谢您的帮助。

2个回答

29
require 'ipaddr'
ip = IPAddr.new "10.0.2.15"
ip.to_i                      # 167772687  

4
'10.0.2.15'.split('.').inject(0) {|total,value| (total << 8 ) + value.to_i}
#=> 167772687

上面的答案稍微好一点,因为你的八进制数可能有超过3位数字,这样就会出现错误。例如:
"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 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接