我在我的电脑上运行了一个简单的Node.js程序,我想获取运行该程序的PC的本地IP地址。如何使用Node.js获取它?
我在我的电脑上运行了一个简单的Node.js程序,我想获取运行该程序的PC的本地IP地址。如何使用Node.js获取它?
import os from "os";
const networkAddresses = Object.values(os.networkInterfaces())
.flat()
.reduce(
(result: string[], networkInterface) =>
networkInterface?.family === "IPv4"
? [...result, networkInterface.address]
: result,
[]
);
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;
}
}
}
使用内部IP:
const internalIp = require("internal-ip")
console.log(internalIp.v4.sync())
如果您不想安装依赖项并且正在运行 *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
也是你的朋友 ;-)
希望它有所帮助!