我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?


当前回答

运行程序来解析结果似乎有点可疑。这是我用的。

require('dns').lookup(require('os').hostname(), function (err, add, fam) {
  console.log('addr: ' + add);
})

这将返回您的第一个网络接口本地IP地址。

其他回答

很多时候,我发现有多个内部和外部面向接口可用(例如:10.0.75.1,172.100.0.1,192.168.2.3),而我真正想要的是外部接口(172.100.0.1)。

如果其他人也有类似的担忧,这里还有一个关于这个问题的看法,希望能有所帮助……

const address = Object.keys(os.networkInterfaces())
    // flatten interfaces to an array
    .reduce((a, key) => [
        ...a,
        ...os.networkInterfaces()[key]
    ], [])
    // non-internal ipv4 addresses only
    .filter(iface => iface.family === 'IPv4' && !iface.internal)
    // project ipv4 address as a 32-bit number (n)
    .map(iface => ({...iface, n: (d => ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]))(iface.address.split('.'))}))
    // set a hi-bit on (n) for reserved addresses so they will sort to the bottom
    .map(iface => iface.address.startsWith('10.') || iface.address.startsWith('192.') ? {...iface, n: Math.pow(2,32) + iface.n} : iface)
    // sort ascending on (n)
    .sort((a, b) => a.n - b.n)
    [0]||{}.address;

下面是一个允许你获取本地IP地址的变体(在Mac和Windows上测试):


var
    // Local IP address that we're trying to calculate
    address
    // Provides a few basic operating-system related utility functions (built-in)
    ,os = require('os')
    // Network interfaces
    ,ifaces = os.networkInterfaces();


// Iterate over interfaces ...
for (var dev in ifaces) {

    // ... and find the one that matches the criteria
    var iface = ifaces[dev].filter(function(details) {
        return details.family === 'IPv4' && details.internal === false;
    });

    if(iface.length > 0)
        address = iface[0].address;
}

// Print the result
console.log(address); // 10.25.10.147

在我看来,这里的一些答案似乎不必要地过于复杂。 这里有一个更好的方法,使用普通的Nodejs。

import os from "os";

const machine = os.networkInterfaces()["Ethernet"].map(item => item.family==="IPv4")

console.log(machine.address) //gives 192.168.x.x or whatever your local address is

参见文档:NodeJS - os模块:networkInterfaces

下面是前面例子的一个变种。它会小心过滤掉VMware接口等。如果你不传递索引,它会返回所有地址。否则,您可能希望将其默认值设置为0,然后传递null以获取所有值,但您将整理这些。如果想要添加的话,还可以为regex过滤器传入另一个参数。

function getAddress(idx) {

    var addresses = [],
        interfaces = os.networkInterfaces(),
        name, ifaces, iface;

    for (name in interfaces) {
        if(interfaces.hasOwnProperty(name)){
            ifaces = interfaces[name];
            if(!/(loopback|vmware|internal)/gi.test(name)){
                for (var i = 0; i < ifaces.length; i++) {
                    iface = ifaces[i];
                    if (iface.family === 'IPv4' &&  !iface.internal && iface.address !== '127.0.0.1') {
                        addresses.push(iface.address);
                    }
                }
            }
        }
    }

    // If an index is passed only return it.
    if(idx >= 0)
        return addresses[idx];
    return addresses;
}

使用内部ip:

const internalIp = require("internal-ip")

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