views:

1114

answers:

3

I can, on some of my systems, get my IP address (192.68.m.n format) by doing this:

addr = IPSocket::getAddress(Socket.gethostname())

...the trouble is that this only works if the name the local machine uses for itself is the name the DNS server associates with it.

How *&#( hard can it be for ruby to just return its primary interface's IP address? I have to do this in a platform-independant way or I'd just call ifconfig or ipconfig and parse it.

A: 

http://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/

EDIT: 6th result when you Google "ruby get IP address."

Can Berk Güder
...doesn't show up at all when I google "ruby get IP address"
have you tried searching without the quotes?
Can Berk Güder
and what's with the downvote? if my answer is offensive in any way, mark it as such. but it's a valid and correct answer, so I think it doesn't deserve a downvote.
Can Berk Güder
+3  A: 

See this question. Also see Socket.getaddrinfo()

Charlie Martin
A: 

How about this

require 'socket'
ipaddr = UDPSocket.open {|s| s.connect('65.59.196.211'); s.addr.last }

the IP address can be anything that is real (this is the I got for stackoverflow.com), but it should be an IP address reachable on the interface you want to get the IP address for. Since its a UDP socket, no connection is actually attempted, but it does try and figure out what interface to use.

john3exonets