[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: To get IP addres of the machine

Roger Pack

1/6/2009 6:23:00 AM

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

1 Answer

Roger Pack

1/7/2009 6:11:00 AM

0

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 :)

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

--
Posted via http://www.ruby-....