Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get my machine's IP address from Ruby without leveraging from other IP address?

Tags:

ruby

sockets

ip

I have searched everywhere but their solution requires some form of IP address. Here are the solutions i have found.

    require 'socket' #METHOD 1     ip = IPSocket.getaddress(Socket.gethostname)     puts ip   #METHOD 2     host = Socket.gethostname     puts host  #METHOD 3(uses Google's address)     ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}     puts ip  #METHOD 4(uses gateway address)     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 '192.168.1.1', 1         s.addr.last       end     ensure       Socket.do_not_reverse_lookup = orig     end      ip=local_ip     puts ip 

All of them require IP address of someone. Is there a solution that does not use someone else's IP address? Preferably, platform independent.

like image 232
user1535147 Avatar asked Jan 01 '13 18:01

user1535147


People also ask

How you can get network address from any IP address?

Enter the command “ipconfig” for Mac or “ifconfig” on Linux. Your computer will then display its own IP address, subnet mask, gateway address, and more, making it possible for you to determine the network number you'll be scanning.

How does an IP address be obtained?

Your IP address is assigned to your device by your ISP. Your internet activity goes through the ISP, and they route it back to you, using your IP address. Since they are giving you access to the internet, it is their role to assign an IP address to your device.

What distributes IP addresses?

How are IP addresses managed and distributed? IP addresses are managed by the Internet Assigned Numbers Authority (IANA), which has overall responsibility for the Internet Protocol (IP) address pool, and by the Regional Internet Registries (RIRs) to which IANA distributes large blocks of addresses.


1 Answers

Isn't the solution you are looking for just:

require 'socket'  addr_infos = Socket.ip_address_list 

Since a machine can have multiple interfaces and multiple IP Addresses, this method returns an array of Addrinfo.

You can fetch the exact IP addresses like this:

addr_infos.each do |addr_info|   puts addr_info.ip_address end 

You can further filter the list by rejecting loopback and private addresses, as they are usually not what you're interested in, like so:

addr_infos.reject( &:ipv4_loopback? )           .reject( &:ipv6_loopback? )           .reject( &:ipv4_private? ) 
like image 72
Itay Grudev Avatar answered Oct 14 '22 05:10

Itay Grudev