Search code examples
erlangelixir

IPv6 Resolution in gen_tcp connect when called from Elixir


When using the connect method of gen_tcp, IPv4 domains are resolved automatically, i.e.:

:gen_tcp.connect('google.com', 443, [:binary, active: false])
{:ok, #Port<0.116>}

However, if resolving an IPv6 domain, it will not resolve correctly

iex(production@b7726c04)3> :gen_tcp.connect('ipv6.google.com', 443, [:binary, active: false])
{:error, :nxdomain}

Am I missing an option with the socket options of :gen_tcp.connect that would enable IPv6 resolution or do I have manually resolve the domain myself before usage? i.e. something like:

:inet_res.resolve('ipv6.google.com', :in, :aaaa)

{:ok,
 {:dns_rec, {:dns_header, 1, true, :query, false, false, true, true, false, 0},
  [{:dns_query, 'ipv6.google.com', :aaaa, :in, false}],
  [
    {:dns_rr, 'ipv6.google.com', :cname, :in, 0, 604606, 'ipv6.l.google.com',
     :undefined, [], false},
    {:dns_rr, 'ipv6.l.google.com', :aaaa, :in, 0, 300,
     {9220, 26624, 16387, 3072, 0, 0, 0, 101}, :undefined, [], false},
    {:dns_rr, 'ipv6.l.google.com', :aaaa, :in, 0, 300,
     {9220, 26624, 16387, 3072, 0, 0, 0, 102}, :undefined, [], false},
    {:dns_rr, 'ipv6.l.google.com', :aaaa, :in, 0, 300,
     {9220, 26624, 16387, 3072, 0, 0, 0, 113}, :undefined, [], false},
    {:dns_rr, 'ipv6.l.google.com', :aaaa, :in, 0, 300,
     {9220, 26624, 16387, 3072, 0, 0, 0, 100}, :undefined, [], false}
  ], [], []}}

Then using the IPv6 tuple directly:

:gen_tcp.connect({9220, 26624, 16387, 3072, 0, 0, 0, 101}, 443, [:binary, active: false])
{:ok, #Port<0.138>}

Solution

  • You can use inet6:

    {ok, P} = gen_tcp:connect("ipv6.google.com", 80, [inet6]).
    {ok,#Port<0.14>}