The most common reason for SocketError
is when your resolver cannot resolve a hostname (domain name). This can happen in any part of your code that uses a domain name instead of an IP address, e.g. email servers, web APIs, message queues, databases etc. In the following example we are trying to make an HTTP request to a server whose domain name is not resolvable, which causes our code to raise SocketError
:
require 'open-uri'
open("http://UnresolvableDomain.com/")
# =>SocketError: Failed to open TCP connection to UnresolvableDomain.com:80
# (getaddrinfo: Name or service not known)
A socket error when you try to resolve an unknown domain:
require 'socket'
begin
puts IPSocket.getaddress("exceptionalcreatures.com")
# => 104.198.14.52
IPSocket.getaddress("SomeUnknownDomain.com")
rescue SocketError => ex
puts ex.inspect
# => <SocketError: getaddrinfo: Name or service not known>
end
SocketError
can also be raised when you use an invalid socket type or an invalid protocol family. However, you wouldn't have this in your typical everyday code.
sock = Socket.new(:INET, :DOGS) # valid types are :STREAM, :DGRAM, :RAW
# => SocketError: unknown socket type: DOGS
sock = Socket.new(:CATS, :STREAM) # a few valid types are: :INET, :INET6, :UNIX
# => SocketError: unknown socket domain: CATS
» Tips
A few common mistakes which cause SocketError
s:
Incorrectly prefixing a protocol like
http://
orftp://
when your function expects just a domain name:IPSocket.getaddress 'google.com' # => "172.217.163.142" IPSocket.getaddress 'http://google.com' # => SocketError: getaddrinfo: Name or service not known
Typos in your domain name.
Missing domain names: You may run into this if you haven't specified a domain name for one of your servers.
Incorrect proxy configuration: Some setups require a valid VPN/proxy to be set up to be able to resolve host names properly. Make sure this isn't an the case.
Misconfigured resolvers: If your server's resolvers aren't set up properly, domain names cannot be resolved. You can check this easily by running
host domainname.com
orping domainname.com
on the server. Make sure that you run these commands from the machine that raised theSocketError
.