19

如何检查端口是否localhost

有没有标准的算法?我正在考虑http向该 url 发出请求并检查响应状态代码是否不是404

4

3 回答 3

26

您可以尝试启动服务器,无论是 TCP 还是 HTTP,都没有关系。然后您可以尝试开始侦听端口,如果失败,请检查错误代码是否为EADDRINUSE.

var net = require('net');
var server = net.createServer();

server.once('error', function(err) {
  if (err.code === 'EADDRINUSE') {
    // port is currently in use
  }
});

server.once('listening', function() {
  // close the server if listening doesn't fail
  server.close();
});

server.listen(/* put the port to check here */);

使用一次性事件处理程序,您可以将其包装到异步检查函数中。

于 2013-10-02T03:40:35.830 回答
12

查看惊人的tcp-port-used 节点模块

//Check if a port is open
tcpPortUsed.check(port [, host]) 

 //Wait until a port is no longer being used
tcpPortUsed.waitUntilFree(port [, retryTimeMs] [, timeOutMs])

//Wait until a port is accepting connections
tcpPortUsed.waitUntilUsed(port [, retryTimeMs] [, timeOutMs])

//and a few others!

我已经在我的gulp 任务中使用这些来watch检测我的 Express 服务器何时安全终止以及它何时再次启动。

这将准确地报告一个端口是否被绑定(不管SO_REUSEADDRand SO_REUSEPORT,正如@StevenVachon 所提到的)。

portscanner NPM 模块将在范围内为您找到空闲和已使用的端口,如果您尝试查找要绑定的开放端口,它会更有用。

于 2016-02-07T09:29:59.310 回答
3

感谢 Steven Vachon 链接,我做了一个简单的例子:

const net = require("net");
const Socket = net.Socket;

const getNextPort = async (port) => {
    return new Promise((resolve, reject) => {
        const socket = new Socket();

        const timeout = () => {
            resolve(port);
            socket.destroy();
        };

        const next = () => {
            socket.destroy();
            resolve(getNextPort(++port));
        };

        setTimeout(timeout, 200);
        socket.on("timeout", timeout);

        socket.on("connect", function () {
            next();
        });

        socket.on("error", function (exception) {
            if (exception.code !== "ECONNREFUSED") {
                reject(exception);
            } else {
                next();
            }
        });

        socket.connect(port, "0.0.0.0");
    });
};

getNextPort(8080).then(port => {
    console.log("port", port);
});
于 2021-02-09T10:12:18.330 回答