Alexander Mills
Alexander Mills

Reputation: 100270

Determine if server is already listening on path to unix domain socket

On Node.js version 10+

Say we have a server listening on a path (unix domain sockets):

const server = net.createServer(socket => {

});

const p = path.resolve(process.env.HOME + '/unix.sock');
server.listen(p);

is there a way to determine if some other server is already listening on path p, before running the above code?

Upvotes: 0

Views: 836

Answers (2)

Dushyant Bangal
Dushyant Bangal

Reputation: 6403

An alternative to my existing answer would be creating a client and trying to connect to the server. Based on the result, you can identify whether the unix socket is taken or not.

function isPortTaken(port, fn) {

    var net = require('net');

    var client = new net.Socket();
    client.connect(port, function(err) {
        if(err)
            return fn(false)

        client.destroy();
        fn(true);

    });

}

Warning: In case the server triggers some action on a new connection, this will trigger it.

Upvotes: 1

Dushyant Bangal
Dushyant Bangal

Reputation: 6403

The easy but kind-of dirty way would be to try and use the port, and see if it throws the EADDRINUSE error.

function isPortTaken(port, fn) {

    var net = require('net')

    var tester = net.createServer()
        .once('error', function (err) {
            if (err.code != 'EADDRINUSE')
                fn(true)
        })
        .once('listening', function () {
            tester.once('close', function () {
                    fn(false)
                })
                .close()
        })
        .listen(port)
}

The callback will give a boolean value.

I was going to write this script myself, but then found it somewhere and made small change to it. You can find the original script here: https://gist.github.com/timoxley/1689041

Upvotes: 1

Related Questions