Ruby: get local IP (nix)

14,961

Solution 1

A server typically has more than one interface, at least one private and one public.

Since all the answers here deal with this simple scenario, a cleaner way is to ask Socket for the current ip_address_list() as in:

require 'socket'

def my_first_private_ipv4
  Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end

def my_first_public_ipv4
  Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
end

Both returns an Addrinfo object, so if you need a string you can use the ip_address() method, as in:

ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?

You can easily work out the more suitable solution to your case changing Addrinfo methods used to filter the required interface address.

Solution 2

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 #google
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

puts local_ip

Found here.

Solution 3

Here is a small modification of steenslag's solution

require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}
Share:
14,961

Related videos on Youtube

fl00r
Author by

fl00r

I am not funny

Updated on June 19, 2020

Comments

  • fl00r
    fl00r over 3 years

    I need to get my IP (that is DHCP). I use this in my environment.rb:

    LOCAL_IP = `ifconfig wlan0`.match(/inet addr:(\d*\.\d*\.\d*\.\d*)/)[1] || "localhost"
    

    But is there rubyway or more clean solution?

  • nhed
    nhed over 11 years
    BTW, I think this is not available in v1.8
  • nhed
    nhed almost 9 years
    Why is that an improvement? @steenslag will run faster as it disables DNS lookups, shorter code is not always better
  • rogerdpack
    rogerdpack almost 8 years
    As a note, ip_address_list was introduced in 1.9.x it seems

Related