convert ip address to 32 bit integer in ruby

懵懂的女人 提交于 2019-12-01 03:33:36
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

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 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!