Created
January 19, 2011 20:55
-
-
Save bradland/786850 to your computer and use it in GitHub Desktop.
Return array of local IP addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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