I'm a Baltimore-based web developer and entrepreneur. I'm the co-founder of Staq, OtherInbox, and Ignite Baltimore. I blog about Ruby, startups, and Baltimore.

Monday, May 12, 2014

Fixing "SocketError: getaddrinfo: Name or service not known" with Ruby's resolv-replace.rb

Update 6/3/2014: there are other advantages to using a pure-Ruby DNS implementation.
Recently we had a problem with DNS lookups for a particular API that only afflicted our Heroku-based workers (host name changed to protect the innocent):

irb(main):009:0> Socket.gethostbyname("example.net")
SocketError: getaddrinfo: Name or service not known

That line of code works fine in other places I tried, like my dev machine. The specific error had to do with a call that Ruby's net/http library was making. I filed a ticket with Heroku support using the above example, and they suggested I try using Ruby's Resolv library, something I had not encountered before. This post is a little breadcrumb to help others who may have the same problem.

Resolv uses Ruby code to do DNS lookups, instead of relying on the system's libc installation like gethostbyname does. Rather than having to monkeypatch net/http, all I had do to was add require "resolv-replace.rb" to our startup code which automatically added this fix. I never found out why the normal lookup process wasn't working on Heroku, but this worked. Thanks to the thoughtful soul who wrote resolv-replace.rb!

I use windows with customized proxy and I get this error: "SocketError Hostname not known: api.stackexchange.com",when I try to "run response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow')" in the console. Any help would be pleasant)))