32 bit IP address to dotted notation in Ruby
Posted by Daniel Brahneborg on 2007 April 13
In one of our applications we store an IP address as a 32 bit integer. To show the value of this field it must be converted to normal dotted notation, and then back again to an integer to get stored in the database.
Going from dotted notation is easy:
require 'ipaddr'
IPAddr.new('1.2.3.4').to_i
Or, the “manual” version:
'1.2.3.4'.split('.').inject(0) {|total,value| (total << 8 ) + value.to_i}
I couldn’t find any examples of going from an integer to dotted notation, so I ended up with this:
address = 0x01020304
[24, 16, 8, 0].collect {|b| (address >> b) & 255}.join('.')
Andra bloggar intressant om: programmering, ruby.

r said
You can convert a decimal ip address to an IPAddr to dotted decimal using the following code:
IPAddr.new(16909060, Socket::AF_INET).to_s
Daniel Brahneborg said
Oh, thanks! That looked a bit cleaner, to say the least.