在Node.js中获取本地IP地址

432

我在我的电脑上运行了一个简单的Node.js程序,我想获取运行该程序的PC的本地IP地址。如何使用Node.js获取它?


1
值得思考的是,可以查看 http://joeyh.name/code/moreutils/ 和 https://github.com/polotek/procstreams。我从不离开家门而没有它们。 - Tegra Detra
尝试一下这个:https://github.com/indutny/node-ip - Stephen Last
44个回答

0
import os from "os";

const networkAddresses = Object.values(os.networkInterfaces())
  .flat()
  .reduce(
    (result: string[], networkInterface) =>
      networkInterface?.family === "IPv4"
        ? [...result, networkInterface.address]
        : result,
    []
  );

0
这是一个更好的工作解决方案(node v18.1.0):
  function getLocalIP() {
      const os = require("os");
      const networkInterfaces = os.networkInterfaces();
      for (const name of Object.keys(networkInterfaces)) {
        for (const net of networkInterfaces[name]) {
          if (net.family == 4 && !net.internal) return net.address;
        }
      }
    }

-2

使用内部IP

const internalIp = require("internal-ip")

console.log(internalIp.v4.sync())

-7

如果您不想安装依赖项并且正在运行 *nix 系统,则可以执行以下操作:

hostname -I

你将获得主机的所有地址,你可以在节点中使用该字符串:

const exec = require('child_process').exec;
let cmd = "hostname -I";
exec(cmd, function(error, stdout, stderr)
{
  console.log(stdout + error + stderr);
});

这是一行代码,您不需要其他库,如'os'或'node-ip',这可能会使您的代码产生意外的复杂性。

hostname -h

也是你的朋友 ;-)

希望它有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接