It turns out to be ridiculously simple. After my testing yesterday, I learned via a comment from Ryan Dahl, that:
all you do is have your Node.js app listen on the IPv6 address.
That’s it.
UPDATE 28 Jul 2014 – As a result of a Reddit thread I’ve seen traffic to this post. Please do note that I wrote this post in early 2011 when I was experimenting with Node.js. I’ve not kept up with the state of Node.js and so 3 years later there may be new or better ways to do what I’ve listed here. Also, please see the comment from Simon Vetter indicating that you don’t need to start up two servers if you simply use “::” as the address. At some point I need to verify that and then update this post.
In a typical application using, say, the “http” module, you will have a line somewhere that says something like:
server.listen(80);
This will bind to your default network interface and address, which, for pretty much all of us, will be our IPv4 address.
To bind to an IPv6 address, you just need to supply the address as an argument to listen(). For example:
server.listen(80, "2001:db8:1111:2222:3333::51"]
So a very basic Node.js app using IPv6 would look like this:
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
response.end ("Hello World!n");
console.log("Got a connection");
});
server.listen(80, "2001:db8:1111:2222:3333::51");
console.log("Server running on localhost at port 80");
Note that as a Node.js app like this will only bind to a single interface and address, this app only listens on the IPv6 address and not on the IPv4 address. To make the app work on both the IPv4 and IPv6 addresses, I need to refactor it a bit into a function that is then called by two different servers that attach to the two network interfaces:
var http = require('http');
var handler = function (request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
response.end ("Hello World!n");
console.log("Got a connection");
};
var server6= http.createServer();
server6.addListener("request",handler);
server6.listen(80,"2001:db8:1111:2222:3333::51");
var server= http.createServer();
server.addListener("request",handler);
server.listen(80,"192.0.2.23");
console.log("Server running on localhost at port 80");
With that in place, it’s now answering on both the IPv4 and IPv6 addresses.
Now this is for the Node.js base modules… other modules may or may not “just work” for IPv6, too, depending upon what they rely on underneath. Regardless, it’s rather cool that it works so easily on IPv6. Kudos to the Node.js team for making it so simple!