Node.js 中获取本机公网 IP

本地开发 Node.js 服务端功能时,大部分情况以 localhost 作为 host 启动服务器。使用公网 IP 启动,则可以在手机或其他任意设备上访问。

以下是 Node.js 中获取本机公网 IP 的工具方法:

function getPublicIP() {
  const os = require("os");
  const ifaces = os.networkInterfaces();
  let en0;

  Object.keys(ifaces).forEach((ifname) => {
    let alias = 0;

    ifaces[ifname].forEach(function (iface) {
      if ("IPv4" !== iface.family || iface.internal !== false) {
        // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
        return;
      }

      if (alias >= 1) {
        // this single interface has multiple ipv4 addresses
        en0 = iface.address;
        console.log(ifname + ":" + alias, iface.address);
      } else {
        // this interface has only one ipv4 adress
        console.log(ifname, iface.address);
        en0 = iface.address;
      }
      ++alias;
    });
  });
  return en0;
};

使用示例:

const Koa = require("koa");
const getPublicIP = require("./util");

const app = new Koa();

const ip = getPublicIP();

app.use(async (ctx) => {
  ctx.body = "Hello World";
});

app.listen(3000,ip);
console.info(`server started at http://${ip}:3000`);
$ node server.js
server started at http://11.22.33.44:3000
$curl http://11.22.33.44:3000
Hello Worl