How do I bind local ipv6 address to my node.js program?

I just created this simple program in nodejs, but i can't bind it to the ipv6 address of my NIC.

I read in the API docs the following

localAddress: Local interface to bind for network connections.

var http = require('http');

var options = {
  hostname: 'www.whatismyipv6.com',
  localAddress: '2a01:xxxx:xxxx:xxxx::2' //a real ipv6 address here
};

var req = http.request(options, function(res) {
  res.on('data', function (chunk) {
    console.log(chunk.toString());
  });
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

req.end();

But when i execute the program i get this. Note the ipv4 address.

<head>
<title>WhatIsMyIPv6? (IPv4: xx.xx.xxx.xxx)</title>
<meta name="bitly-verification" content="984886d337a6"/>
</head>

It looks like nodejs is ignoring the localAddress and is binding directly to the ipv4 address.

# node --version
v0.8.0

It is possible to force node to connect using ipv6, at least it works on node v0.12.7. Your options will look like this:

var options = {
  hostname: 'www.whatismyipv6.com',
  localAddress: '2a01:xxxx:xxxx:xxxx::2', //a real ipv6 address here
  family: 6
};

Unfortunately you're out of luck on this one, and with any other host that has both A and AAAA RRs published.

http.js doesn't pass an addressType ( address family ) down the stack, so at the bottom of the call the lookup() func in dns.js just issues a general getaddrinfo() call and takes the first returned result, which is the A RR for the target host's IPv4 address in this example.

If you check dns.js you can see that lookup() just pops address[0] off the results when no family is specified:

function onanswer(addresses) {
    if (addresses) {
      if (family) {
        callback(null, addresses[0], family);
      } else {
        callback(null, addresses[0], addresses[0].indexOf(':') >= 0 ? 6 : 4);
      }
    } else {
      callback(errnoException(process._errno, 'getaddrinfo'));
    }
  }

As you can see it does make an effort to set the family for that result; in your example, the first result is identified as IPv4 family and as this percolates back up the stack binding is completed accordingly, over-riding your localAddress specification.

You can see this by changing your target host to ipv6.whatismyipv6.com; magically, your localhost's IPv6 address is now bound as you desired.