Skip to content

Instantly share code, notes, and snippets.

@bradland
Created Jan 19, 2011
Embed
What would you like to do?
Return array of local IP addresses
require 'socket'
# Base on answer from http://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails
# return an array of local IP addresses
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '4.2.2.1', 1 # as this is UDP, no connection will actually be made
s.addr.select {|ip| ip =~ /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/}.uniq
end
ensure
Socket.do_not_reverse_lookup = orig
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment