0

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.

Jon Seigel
  • 12,035
  • 8
  • 56
  • 92
Sniggerfardimungus
  • 11,195
  • 10
  • 49
  • 93

2 Answers2

4

See this question. Also see Socket.getaddrinfo()

Community
  • 1
  • 1
Charlie Martin
  • 107,118
  • 23
  • 189
  • 257
0

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.