Ruby: get local IP (nix) Ruby: get local IP (nix) unix unix

Ruby: get local IP (nix)


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?}enddef 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.


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  endensure  Socket.do_not_reverse_lookup = origendputs local_ip

Found here.


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}