views:

167

answers:

2

Is there an easy way in Ruby for me to get a list of the IP addresses for all network interfaces? It needs to work in Linux/Win/OSX and I'd prefer to not have to parse ifconfig/ipconfig unless I absolutely have to.

+1  A: 

I don't think ruby has a standard api for this but under some assumptions this should be fairly reliable across platforms:

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

Here we are assuming quite a few things like the machine having a local hostname pointing to the correct ip addresses. So, this is definitely not completely reliable but it's platform independent and works on the common setups.

Edit: If you decide to get down to parsing ifconfig, consider forking ruby-ifconfig. It claims to do that on most non-windows platforms already.

anshul
"_service_ is a service name ("http", "ssh", …), or a port number (80, 22, …)", so :echo => 'echo'
aaz
The hostname requirement kills this for me.. On a machine with 4 interfaces I just get back ["127.0.0.1", "127.0.0.1"]
Tindron
Ummm... Is the tool you are writing server side? Is using snmp an option?
anshul
A: 

Check out the following post:

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

There's also a discussion on the solution anshul posted in the comments.

Michael Kohl
That method works great if I know IP addresses I want to connect to for each interface. Unfortunately I can't assume that.. according to the comments Ruby has no API for this so I guess it's ifconfig/ipconfig for me.
Tindron