http-party / node-portfinder

A simple tool to find an open port or domain socket on the current machine
https://github.com/http-party/node-portfinder
Other
887 stars 95 forks source link

Why don't use net.connect #95

Closed TingYinHelen closed 4 years ago

TingYinHelen commented 5 years ago

I use net.connect() to write same function. It is faster than use net.createServer.

const net = require('net');

exports.basePort = 8000
exports.highestPort = 65535

let port = exports.basePort
const internals = {}

internals.nextPort = () => {
    port++
    return port
}

exports.getPort = (callback) => {
    const c = net.connect({ port }, '127.0.0.1')
    c.once('error', (e) => {
        callback(null, port)
    })
    c.once('connect', () => {
        c.destroy();
        if (port < exports.highestPort) {
            port = internals.nextPort()
            exports.getPort(callback)
        } else {
            callback(new Error('No open ports available'));
        }
    })
}

image

flymzero commented 5 years ago

抓到一个小姐姐 if connection blocking, it will do 'error' event or 'timeout' event ?🤔

TingYinHelen commented 5 years ago

抓到一个小姐姐 if connection blocking, it will do 'error' event or 'timeout' event ?🤔

error, I have been test

eriktrom commented 5 years ago

I use net.connect() to write same function. It is faster than use net.createServer.

They are different.

Regardless, ops/sec for a development port finding library used primarily by CI servers, webpack and similar local CI/development tools don't need ops/sec improvements.

They do however need to ensure that a port and host are available for use on interfaces that are not privileged or reserved.

If you want to port scan production servers, there is a python library out there that works well. I don't recall the name. Or you could write one in rust/c++.

I will double check the node docs again though (it's been over 2 years for this api).

If you can provide reasoning or the underlying os's syscall's, via links to node docs or man pages for underlying libuv calls from node, I will look much sooner - else, will close in a month or so if i don't get to (assuming there is no follow up in this thread from ya'll).

Thanks for your input.

eriktrom commented 4 years ago

closing to prevent stale issues. feel free to re-open if interest in further discussion remains