To get IP addres of the machine

Sijo Kg wrote:

Hi
Could you please tell the code to get the IPaddress of my machine

This might work:

class Socket
  class << self
    def get_ip hostName
      begin
       ipInt = gethostbyname(hostName)[3]
        return "%d.%d.%d.%d" % [ipInt[0].ord, ipInt[1].ord,
ipInt[2].ord, ipInt[3].ord]
      rescue SocketError # bizarre, but happens
        return ''
      end
    end

    def get_host_ip
      begin
        ip = Socket.getaddrinfo(Socket.gethostname, nil,
Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil,
Socket::AI_CANONNAME).select{|type| type[0] == 'AF_INET'}[0][3] # ltodo
hmm we don't want it to do the reverse lookups!
        raise if ip.blank?
        return ip
      rescue => e
        get_ip(Socket.gethostname) # less accurate or something, I guess
      end
    end

  end
end

···

--
Posted via http://www.ruby-forum.com/\.

Roger Pack wrote:

Sijo Kg wrote:

Hi
Could you please tell the code to get the IPaddress of my machine

heh
it was for 1.9 anyway :slight_smile:

let's see
require 'socket'
class Fixnum
def ord
  self
end
end
# the code above
Socket.get_host_ip

···

--
Posted via http://www.ruby-forum.com/\.