13

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.

Dave Schweisguth
  • 34,335
  • 10
  • 90
  • 114
Rajesh Omanakuttan
  • 6,660
  • 6
  • 44
  • 83

3 Answers3

25

Use Socket::ip_address_list.

Socket.ip_address_list #=> Array of AddrInfo
user513951
  • 11,572
  • 7
  • 61
  • 75
Sigurd
  • 7,571
  • 3
  • 23
  • 33
  • can you please suggest how we could get the second value from the array that we get by using "Socket.ip_address_list #=> Array of AddrInfo". I am not getting that in normal way. Thanks – Rajesh Omanakuttan Dec 24 '12 at 09:42
  • 9
    Second is not always proper one. You might have number of different interfaces and loopbacks. You can use following code to reject all "local" addresses and expose first external `Socket.ip_address_list.find {|a| a.ipv4? ? !(a.ipv4_private? || a.ipv4_loopback?) : !(a.ipv6_sitelocal? || a.ipv6_linklocal? || a.ipv6_loopback?) }` – Sigurd Dec 24 '12 at 09:54
  • 5
    What exactly is not working? And please provide your AddrInfo array. May be your machine does not own remote ip, sou you need to drop ipv4_private? and ipv6_sitelocal? from conditions in order to get local subnet ip. – Sigurd Dec 24 '12 at 10:54
  • OP asks for local IP (assuming IPv4), so: `puts Socket.ip_address_list.find { |a| a.ipv4_private? && !a.ipv4_loopback? }.ip_address` – bradw2k Jul 15 '21 at 19:26
3

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
the Tin Man
  • 155,156
  • 41
  • 207
  • 295
SSP
  • 2,699
  • 5
  • 29
  • 49
  • can you please suggest how we could get the second value from the array that we get by using "Socket.ip_address_list #=> Array of AddrInfo". I am not getting that in normal way. Thanks – Rajesh Omanakuttan Dec 24 '12 at 09:41
2

Write below method

def self.local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
    UDPSocket.open do |s|
      s.connect '64.233.187.99', 1
      s.addr.last
    end
    ensure
      Socket.do_not_reverse_lookup = orig
 end

and then call local_ip method, you will get ip address of your machine.

Eg: ip_address= local_ip
Dipali Nagrale
  • 500
  • 5
  • 16