jared tame

there is no spoon. 
« Back to blog

using ruby sockets to find ip addresses

i'm surprised it's this verbose to find your ip address in ruby, but here it is:

require 'socket'

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 '64.233.187.99', 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

# irb:0> local_ip


# => "192.168.0.127"

also, try this one out too if you're using a specific port:

def index
@local_ip = local_ip
    if @local_ip == "192.168.1.12"
      @local_ip = "localhost:3000"
    end
end

 

edit: as it turns out, you will almost never need to do this.

Comments (0)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    Connect    twitter