Search code examples
arraysrubyip-address

How to manually convert an integer into an IP address in Ruby


Can anyone assist me in manually converting an integer into an IP address?

I understand the concept, but I am struggling to figure out the process; the number 631271850, has an IP address of '37.160.113.170'.

I know that an IP address is made up of four octets and the solution I have to manually converting an IP address into a number is:

def ip_to_num(ip_address)
  array = ip_address.split('.').map(&:to_i)
  ((array[0] * 2**24) + (array[1] * 2**16) + (array[2] * 2**8) + (array[3]))
end

To do the reverse is puzzling me. How do I convert it back?


Solution

  • An IP is just a 32-bit integer representing a 4-byte array:

    [631271850].pack('N').unpack('CCCC').join('.')
    => "37.160.113.170"
    

    Just for fun, another way to convert IP to int:

    "37.160.113.170".split(".").map(&:to_i).pack('CCCC').unpack('N')[0]
    => 631271850