Mysterious ECONNREFUSED with net.connect in Node

Hit a minor gotcha playing with Node on the Mac recently.

In an app I'm working on I'd set up a simple Lua repl you can telnet into and it works fine. I've got an idea for making an application specific repl using Node Webkit so I started to write simple node to connect to my application repl:

var net = require('net');

var port = 6502;
var host = 'localhost';

var socket = net.connect(port,host, function() {
    console.log("Sending data");

    socket.on("data", function (data) {
        console.log("received data");
        console.log( data.toString() );
        socket.end();
    })
})

socket.on("error", function(err) {
    console.log("Error");
    console.log(err);
})

Only it won't connect. The lua code is pretty simple and binds to localhost:6502 as well, it works fine with nc or telnet but no beans here. All I get back is a connection refused JSON packet

Error
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }

It turns out that the lua socket code I'm using will set up an IPV6 socket when I bind to 'localhost' while net.connect will try and connect via IPV4. Telent and NC don't care and just detects the type of connection to rightly use.

The solutions are either change the node code to bind to '::1', IPV6's localhost equivalent and connect via IPV6 or changed my server code so it binds to 127.0.0.1. Both work and I went for the latter.

There's a lot of things at play here and I don't which one of the many components (if any) aren't playing sensibly. Should localhost always default to IPV6? Should net.connect try and establish an IPV6 connection if it can't make an IPV4 one? I dunno, I'm pretty new to this but it chewed up enough of my Sunday to want to write it down in case anyone else had the same woes :)

comments powered by Disqus