在ruby中将ip地址转换为32位整数 [英] convert ip address to 32 bit integer in ruby
本文介绍了在ruby中将ip地址转换为32位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到一种方法将Ruby地址中的IP地址转换为32位整数用于木偶模板。
I am trying to find a way to convert a ip address to a 32 bit integer in Ruby for a puppet template.
这就是我在转换中的方式bash。
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
这篇关于在ruby中将ip地址转换为32位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文