[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

Brian Candler

1/6/2009 9:07:00 AM

Sijo Kg wrote:
> Could you please tell the code to get the IPaddress of my machine

Your machine may have multiple IP addresses, but assuming its hostname
has been set up properly, the following may do the trick:

require 'socket'
ip = IPSocket.getaddress(Socket.gethostname)
--
Posted via http://www.ruby-....

2 Answers

ab5tract

1/6/2009 8:12:00 PM

0

> Sijo Kg wrote:
> > Could you please tell the code to get the IPaddress of my machine

Another way to do this:

require 'ipaddr'
require 'net/http'

def get_ip
con = Net::HTTP.new('checkip.dyndns.org', 80)
resp,body = con.get("/", nil)
ip = body.match(/\d+\.\d+\.\d+\.\d+/)

ip[0]
end

my_ip = IPAddr.new(get_ip)

I had to do this as a work around before, though if I was working
around an issue with Socket.gethostname or my own ignorance I can no
longer tell ;)

Gary Wright

1/6/2009 9:10:00 PM

0


On Jan 6, 2009, at 3:15 PM, ab5tract wrote:
> Another way to do this:
>
> require 'ipaddr'
> require 'net/http'
>
> def get_ip
> con = Net::HTTP.new('checkip.dyndns.org', 80)
> resp,body = con.get("/", nil)
> ip = body.match(/\d+\.\d+\.\d+\.\d+/)
>
> ip[0]
> end
>
> my_ip = IPAddr.new(get_ip)
>
> I had to do this as a work around before, though if I was working
> around an issue with Socket.gethostname or my own ignorance I can no
> longer tell ;

It is important to realize that this method won't take into account
any sort of NAT device that may be between you and an external website.
Whether that is important or not depends on the reason for needing an
IP address in the first place.