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


当前回答

我所知道的就是我想要以192.168开头的IP地址。这段代码会给你:

function getLocalIp() {
    const os = require('os');

    for(let addresses of Object.values(os.networkInterfaces())) {
        for(let add of addresses) {
            if(add.address.startsWith('192.168.')) {
                return add.address;
            }
        }
    }
}

当然,如果你想要一个不同的数字,你可以改变数字。

其他回答

这是我的变体,允许以可移植的方式获得IPv4和IPv6地址:

/**
 * Collects information about the local IPv4/IPv6 addresses of
 * every network interface on the local computer.
 * Returns an object with the network interface name as the first-level key and
 * "IPv4" or "IPv6" as the second-level key.
 * For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
 * (as string) of eth0
 */
getLocalIPs = function () {
    var addrInfo, ifaceDetails, _len;
    var localIPInfo = {};
    //Get the network interfaces
    var networkInterfaces = require('os').networkInterfaces();
    //Iterate over the network interfaces
    for (var ifaceName in networkInterfaces) {
        ifaceDetails = networkInterfaces[ifaceName];
        //Iterate over all interface details
        for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
            addrInfo = ifaceDetails[_i];
            if (addrInfo.family === 'IPv4') {
                //Extract the IPv4 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv4 = addrInfo.address;
            } else if (addrInfo.family === 'IPv6') {
                //Extract the IPv6 address
                if (!localIPInfo[ifaceName]) {
                    localIPInfo[ifaceName] = {};
                }
                localIPInfo[ifaceName].IPv6 = addrInfo.address;
            }
        }
    }
    return localIPInfo;
};

下面是同一个函数的CoffeeScript版本:

getLocalIPs = () =>
    ###
    Collects information about the local IPv4/IPv6 addresses of
      every network interface on the local computer.
    Returns an object with the network interface name as the first-level key and
      "IPv4" or "IPv6" as the second-level key.
    For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
      (as string) of eth0
    ###
    networkInterfaces = require('os').networkInterfaces();
    localIPInfo = {}
    for ifaceName, ifaceDetails of networkInterfaces
        for addrInfo in ifaceDetails
            if addrInfo.family=='IPv4'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv4 = addrInfo.address
            else if addrInfo.family=='IPv6'
                if !localIPInfo[ifaceName]
                    localIPInfo[ifaceName] = {}
                localIPInfo[ifaceName].IPv6 = addrInfo.address
    return localIPInfo

console.log(getLocalIPs())的示例输出

{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
  wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
  tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }

如果你不想安装依赖,并且正在运行*nix系统,你可以这样做:

hostname -I

你会得到主机的所有地址,你可以在node中使用这个字符串:

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

也是你的朋友;-)

希望能有所帮助!

谷歌在搜索“Node.js获取服务器IP”时引导我到这个问题,所以让我们为那些试图在他们的Node.js服务器程序中实现这一点的人提供一个替代答案(可能是原始海报的情况)。

在最简单的情况下,服务器只绑定到一个IP地址,应该不需要确定IP地址,因为我们已经知道将它绑定到哪个地址(例如,传递给listen()函数的第二个参数)。

在不太简单的情况下,服务器绑定到多个IP地址,我们可能需要确定客户端连接到的接口的IP地址。正如Tor Valamo所简单建议的,现在,我们可以很容易地从连接的套接字及其localAddress属性中获得这些信息。

例如,如果程序是web服务器:

var http = require("http")

http.createServer(function (req, res) {
    console.log(req.socket.localAddress)
    res.end(req.socket.localAddress)
}).listen(8000)

如果它是一个通用TCP服务器:

var net = require("net")

net.createServer(function (socket) {
    console.log(socket.localAddress)
    socket.end(socket.localAddress)
}).listen(8000)

在运行服务器程序时,该解决方案提供了非常高的可移植性、准确性和效率。

详情请参见:

http://nodejs.org/api/net.html http://nodejs.org/api/http.html

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

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

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

公认的答案是异步的。我想要一个同步版本:

var os = require('os');
var ifaces = os.networkInterfaces();

console.log(JSON.stringify(ifaces, null, 4));

for (var iface in ifaces) {
  var iface = ifaces[iface];
  for (var alias in iface) {
    var alias = iface[alias];

    console.log(JSON.stringify(alias, null, 4));

    if ('IPv4' !== alias.family || alias.internal !== false) {
      debug("skip over internal (i.e. 127.0.0.1) and non-IPv4 addresses");
      continue;
    }
    console.log("Found IP address: " + alias.address);
    return alias.address;
  }
}
return false;