Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting IP address from hostnames in Ruby

Tags:

ruby

I have a Ruby array, server_names, that stores hostnames. If I print it out, it looks something like this:

["hostname.abc.com", "hostname2.abc.com", "hostname3.abc.com"]

Pretty standard. What I'm trying to do is get the IPs of those servers (maybe store them in another variable).

It looks like the IPSocket class might do it, but I'm not sure how to iterate through it using the IPSocket class. If it just try to print out the IPs like:

server_names.each do |name|
            IPSocket::getaddress(name)
            p name
          end

it complains that I didn't provide a server name. Is this a syntax issue or am I just not using the class correctly?

Output:

getaddrinfo: nodename nor servname provided, or not known
like image 685
mxmxx Avatar asked Feb 17 '17 22:02

mxmxx


2 Answers

You might be better off using Resolv, which is part of the Ruby standard library and is specifically designed to handle resolving DNS entries.

From the Ruby docs:

Resolv is a thread-aware DNS resolver library written in Ruby. Resolv can handle multiple DNS requests concurrently without blocking the entire Ruby interpreter.

Example:

require "resolv"

server_names.each do |name|
  address = Resolv.getaddress(name)
  puts address
end
like image 133
Steven Schobert Avatar answered Oct 19 '22 10:10

Steven Schobert


That's just how the getaddrinfo method works. If the name can be resolved you get an IP address expressed as a string. If not you get a SocketError exception. That means in order to handle these you need to anticipate that:

server_names.map do |name|
  begin
    IPSocket.getaddress(name)
  rescue SocketError
    false # Can return anything you want here
  end
end

Note that when calling methods on things it's convention to use . and not the namespace separator ::. The separator does work but it's messy as that's usually reserved for referencing constants like MyClass::MY_CONST.

like image 7
tadman Avatar answered Oct 19 '22 10:10

tadman