On Wed, Nov 19, 2008 at 8:43 AM, Vladimir Fekete
<fekete / melkor.dnp.fmph.uniba.sk> wrote:
>
> Hi *,
>
> Could you pleas help me with following problem ?
>
> I need to get  FQDN of host as well as it's IP. So I need same result as
> "host" command gives me in *nix OSes. I found out these (suitable) functions:
>
> Socket.getaddrinfo
> IPSocket.getaddress
> TCPSocket.gethostbyname
>
> which can do the job (partialy). My problem is that non of them gives me
> back FQDN. Eg. let's say that I have myserver.mydomain.com which is FQDN and
> it's alias is myserver.
>
> My problem is that when I use any of those functions with "myserver"
> attribiute I always get as set of aliases ["myserver"] array only (e.g. no
> myserver.mydomain.com).
>
> Is there any way how to find out FQDN via some ruby function ? Thanks!
>
> Regards,
>
>  V.
>

gethostbyname and gethostbyaddr both return the "canonical name" in the first
element of the output array. If you are dealing with IP addresses gethostbyaddr
can do a reverse lookup for you (but not gethostbyname).

One tricky bit is that gethostbyaddr expects a struct in_addr packed into a
Ruby string.  See inet_ntoa below to help with that.

Examples:

require 'socket'
def inet_aton(ip)
    ip.split('.').inject(String.new) { |str, q| str << q.to_i }
end

p Socket.gethostbyname('www.google.com')[0]
p Socket.gethostbyaddr(inet_aton("127.0.0.1"))[0]