Skip to content

Support address family any when making connections #10

@torhve

Description

@torhve

I have a suggestion for a patch, but I'm very unsure on how to best do it.

Problem is that current lua-handler doesn't do getaddrinfo before making a new socket, which means that for example a http client using lua-handlers will always just use IPv4 unless you give it an explicit IPv6-address.

My fix is to explicitly call getaddrinfo from nixio to use the first result it returns. It probably could be smarter her any try all the results in order and see which it actually can connect to in case of problems.

Thoughts?

 --- lua-handlers/handler/connection.lua|2015-05-13 14:31:54.061867145 +0000
 +++ handler/connection.lua| 2015-05-13 14:30:49.989828832 +0000
 @@ -385,23 +385,29 @@
  end

  local function sock_new_connect(loop, handler, domain, _type, host, port, laddr, lport)
 -  -- create nixio socket
 -  local sock = new_socket(domain, _type)
 -  -- wrap socket
 -  local self = sock_wrap(loop, handler, sock)
 -  -- bind to local laddr/lport
 -  if laddr then
 -     n_assert(sock:setsockopt('socket', 'reuseaddr', 1))
 -     n_assert(sock:bind(laddr, tonumber(lport or 0)))
 -  end
 -  -- connect to host:port
 -  local ret, errno, err = sock:connect(host, port)
 -  if not ret and errno ~= EINPROGRESS then
 -     -- report error
 -     sock_handle_error(self, err)
 -     return nil, err
 -  end
 -  return self
 +    -- Do lookup so we know what kind of socket to create
 +    local addrinfs = nixio.getaddrinfo(host, 'any')
 +    for i=1, #addrinfs do
 +        local addrinf = addrinfs[i]
 +        -- create nixio socket
 +        local sock = new_socket(addrinf.family, _type)
 +        -- wrap socket
 +        local self = sock_wrap(loop, handler, sock)
 +        -- bind to local laddr/lport
 +        if laddr then
 +            n_assert(sock:setsockopt('socket', 'reuseaddr', 1))
 +            n_assert(sock:bind(laddr, tonumber(lport or 0)))
 +        end
 +        -- connect to resolved host:port
 +        local ret, errno, err = sock:connect(addrinf.address, port)
 +        print (addrinf.address, host, port, laddr, ret, errno, err)
 +        if not ret and errno ~= EINPROGRESS then
 +            -- report error
 +            sock_handle_error(self, err)
 +            return nil, err
 +        end
 +        return self
 +    end
  end
  -- remove '[]' from IPv6 addresses

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions