开发者

Ruby - Platform independent way to determine IPs of all network interfaces?

开发者 https://www.devze.com 2022-12-23 04:57 出处:网络
Is there an easy way in Ruby for me to get a list of the IP addresses for all network interfaces?It ne开发者_如何学运维eds to work in Linux/Win/OSX and I\'d prefer to not have to parse ifconfig/ipconf

Is there an easy way in Ruby for me to get a list of the IP addresses for all network interfaces? It ne开发者_如何学运维eds to work in Linux/Win/OSX and I'd prefer to not have to parse ifconfig/ipconfig unless I absolutely have to.


As of Ruby 2.1, Socket#getifaddrs 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"]


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消