Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bradland
Created January 19, 2011 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradland/786850 to your computer and use it in GitHub Desktop.
Save bradland/786850 to your computer and use it in GitHub Desktop.
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