Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: get local IP (nix)

Tags:

unix

ruby

ip

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?

like image 854
fl00r Avatar asked Feb 17 '11 13:02

fl00r


3 Answers

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.

like image 120
Claudio Floreani Avatar answered Oct 18 '22 00:10

Claudio Floreani


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.

like image 39
steenslag Avatar answered Oct 18 '22 00:10

steenslag


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}
like image 37
D-D-Doug Avatar answered Oct 18 '22 01:10

D-D-Doug