Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the IP address of my local machine in Ruby?

I am doing Rails development in Ubuntu 12.04LTS OS.

I want to capture my local IP address in a file, not the loopback 127.0.0.1, the one which I get using ifconfig. Please suggest a solution.

like image 967
Rajesh Omanakuttan Avatar asked Dec 24 '12 09:12

Rajesh Omanakuttan


People also ask

How do I find my local server IP address?

Open the Start menu and type cmd to open the Command Prompt. Type ipconfig into the Command Prompt and press Enter. The tool will return a set of data that includes your IP address.

What IP address is?

Here's how to find the IP address on the Android phone:Go to your phone's settings. Select “About device.” Tap on “Status.” Here you can find information about your device, including the IP address.


2 Answers

Use Socket::ip_address_list.

Socket.ip_address_list #=> Array of AddrInfo
like image 149
Sigurd Avatar answered Oct 24 '22 13:10

Sigurd


This is my first way:

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"

This is my second way, which is not recommended:

require 'socket'
 Socket::getaddrinfo(Socket.gethostname,”echo”,Socket::AF_INET)[0][3]

The third way:

 UDPSocket.open {|s| s.connect('64.233.187.99', 1); s.addr.last }

And a fourth way:

Use Socket#ip_address_list

Socket.ip_address_list #=> Array of AddrInfo
like image 24
SSP Avatar answered Oct 24 '22 13:10

SSP