Does anyone have good ipaddress to decimal number code working well?

I’ve been looking at various approaches to identifying MySQL slaves uniquely, and would love to use the IP address converted to normal decimal to set the MySQL “server-id”. My concern is that I also need to check for error conditions, such as hosts that use IPv6 only and may need a different algorithm.

Does anyone have a chunk of code buried in a cookbook or template somewhere that might do this well for me., and save me some noticeable work?

Nico Kadel-Garcia
Lead DevOps Engineer
nkadel@skyhookwireless.com

what about taking the first few characters from /etc/machine-id ?

irb(main):001:0> '192.168.0.1'.split('.').map {|e| e.to_i}.pack('C4').unpack('N') => [3232235521] irb(main):002:0> a = '192.168.0.1'.split('.').map {|e| e.to_i} => [192, 168, 0, 1] irb(main):003:0> a[0] * 256 ** 3 + a[1] * 256 ** 2 + a[2] * 256 ** 1 + a[3] * 256 ** 0 => 3232235521 irb(main):004:0>
You could use IPAddr.new as an address check:
irb(main):005:0> require 'ipaddr' => true irb(main):006:0> IPAddr.new('192.168.0.1') => #<IPAddr: IPv4:192.168.0.1/255.255.255.255> irb(main):007:0> IPAddr.new('192.168.0.300') IPAddr::InvalidAddressError: invalid address from /opt/chefdk/embedded/lib/ruby/2.1.0/ipaddr.rb:529:in `block in in_addr' from /opt/chefdk/embedded/lib/ruby/2.1.0/ipaddr.rb:528:in `each' from /opt/chefdk/embedded/lib/ruby/2.1.0/ipaddr.rb:528:in `inject' from /opt/chefdk/embedded/lib/ruby/2.1.0/ipaddr.rb:528:in `in_addr' from /opt/chefdk/embedded/lib/ruby/2.1.0/ipaddr.rb:490:in `initialize' from (irb):10:in `new' from (irb):10 from /opt/chefdk/embedded/bin/irb:11:in `<main>' irb(main):008:0>
The family method can be used to determine whether it’s an IPv4 or IPv6 address.

Hth,
Jos

Interestingly, you can use the .to_i method of the ipaddr object to do the conversion to decimal:

[1] pry(main)> require 'ipaddr'
=> true
[2] pry(main)> IPAddr.new("192.168.0.1").to_i
=> 3232235521

I didn’t even try that, but it makes perfect sense in the case of an IPv4 address (and returns a Bignum in the case of an IPv6 address).

Thanks, Mark.

Looking back on this thread:

I wasn’t looking for raw ruby. I was looking for chef compatible code, for embedding in a template or a recipe.