Rss Feed Tweeter button Facebook button Technorati button Reddit button Linkedin button Webonews button Delicious button Digg button Flickr button Stumbleupon button Newsvine button

A Waage Blog

Ruby, Rails, Life

Archive for the ‘socket’ tag

Resolve a hostname from an IP address in Ruby (Reverse-DNS)

with one comment

It sounds easy, but I tried a lot of things before finding the solution I used.

I tried using:

`host 66.249.67.49` or
`nslookup 66.249.67.49`

These were fine, but it seems a bit hacky to use the shell. Also, it would require some sort of parsing to get the hostname that I want.

Browsing the web, I found a couple solutions that almost worked.

s = Socket.getaddrinfo('66.249.67.49',nil)
hostname = s[0][2]

This solution worked in IRB, worked in console, but for some reason would not work when I was running my mongrel server and trying to perform the exact same method call from a web-browser. ( I still don’t know why).

Digging around a bit more, I came up with this simple solution:

host = Resolv.new.getname('66.249.67.49')

Is it really that easy?? Give it a shot and let me know your thoughts !!

Written by Andrew Waage

October 9th, 2009 at 2:47 pm