June 20th, 2005


TCPServer and IPv6

Somebody posted to ruby-core about how they had to create two TCPServer instances before they could connect. Since they were running IPv6, the first TCPServer bound to the IPv6 socket, and the second to the IPv4 socket. I imagine their hosts file is incorrect, so they always tried to connect to the IPv4 socket.

Here's the right way to connect to both IPv6 and IPv4 sockets, if your OS supports both:

require 'socket'
res = Socket.getaddrinfo(nil, 1234, Socket::AF_UNSPEC,
                         Socket::SOCK_STREAM, 0, Socket::AI_PASSIVE)
sockets = []

res.each do |ai|
  sockets << TCPServer.new(ai[3], ai[1])