In Ruby, how do I get my IP octet without going through DNS?

On some of my systems, I can get my IP address (192.68.mn format) by doing the following:

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

      

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

Like * & # (is it hard for Ruby to just get back its primary IP address of the interface? I have to do it in a platform independent way, or just call ifconfig or ipconfig and parse it.

0


source to share


2 answers


See this question . Alsosee Socket.getaddrinfo()



+4


source


How about this

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

      



The IP address can be any real one (I got this for stackoverflow.com), but it must be an IP address available on the interface for which you want the IP address. From its UDP socket, no connection is actually made, but it is trying to figure out which interface to use.

0


source







All Articles