convert ip address to 32 bit integer in ruby

前端 未结 2 529
我在风中等你
我在风中等你 2021-01-11 18:04

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@u         


        
相关标签:
2条回答
  • 2021-01-11 18:13
    '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 }
    
    0 讨论(0)
  • 2021-01-11 18:25
    require 'ipaddr'
    ip = IPAddr.new "10.0.2.15"
    ip.to_i                      # 167772687  
    
    0 讨论(0)
提交回复
热议问题