Ruby - a platform-independent way to determine the IP addresses of all network interfaces?

Is there an easy way in Ruby to get a list of IP addresses for all network interfaces? It should work on Linux / Win / OSX, and I would prefer not to understand ifconfig / ipconfig unless I need it.

+7
ruby interface networking ip-address
source share
3 answers

As in Ruby 2.1, the # getifaddrs socket is available:

001:0> require 'socket' => true 002:0> Socket.getifaddrs.map { |i| i.addr.ip_address if i.addr.ipv4? }.compact => ["127.0.0.1", "192.168.1.121", "192.168.1.181"] 
+8
source share

Pay attention to the following message:

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

It also discusses the anshul solution posted in the comments.

+2
source share

I don't think Ruby has a standard api for this, but under some assumptions this should be fairly reliable on different platforms:

 require 'socket' Socket::getaddrinfo(Socket.gethostname, 'echo', Socket::AF_INET).map { |x| x[3] } 

Here we take a lot of things like a machine with a local host name pointing to the correct IP addresses. Thus, it is definitely not completely reliable, but it is platform independent and works with general settings.

Edit: if you decide to move on to ifconfig analysis, consider forking ruby-ifconfig . He claims to do this on most non-Windows platforms.

+1
source share

All Articles