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?
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.