Javascript 在 node.js 中获取本地 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3653065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:36:24  来源:igfitidea点击:

Get local IP address in node.js

javascriptnode.jsip

提问by yojimbo87

I have a simple node.js program running on my machine and I want to get local IP address of PC on which my program is running. How do I get it with node.js?

我有一个简单的 node.js 程序在我的机器上运行,我想获取运行我的程序的 PC 的本地 IP 地址。我如何使用 node.js 获取它?

回答by nodyou

'use strict';

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

Object.keys(ifaces).forEach(function (ifname) {
  var 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
      console.log(ifname + ':' + alias, iface.address);
    } else {
      // this interface has only one ipv4 adress
      console.log(ifname, iface.address);
    }
    ++alias;
  });
});

// en0 192.168.1.101
// eth0 10.0.0.101

回答by Xedecimal

os.networkInterfaces as of right now doesn't work on windows.Running programs to parse the results seems a bit iffy. Here's what I use.

os.networkInterfaces 目前在 Windows 上不起作用。运行程序来解析结果似乎有点不确定。这是我使用的。

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

This should return your first network interface local ip.

这应该返回您的第一个网络接口本地 ip。

回答by Jan J?na

https://github.com/indutny/node-ip

https://github.com/indutny/node-ip

var ip = require("ip");
console.dir ( ip.address() );

回答by Edoardo

Any IP of your machine you can find by using the osmodule - and that's nativeto NodeJS

您可以使用os模块找到您机器的任何 IP - 这是NodeJS原生的

var os = require( 'os' );

var networkInterfaces = os.networkInterfaces( );

console.log( networkInterfaces );

All you need to do is call os.networkInterfaces()and you'll get an easy manageable list - easier than running ifconfigby leagues

您需要做的就是调用os.networkInterfaces(),您将获得一个易于管理的列表 - 比通过联盟运行ifconfig更容易

http://nodejs.org/api/os.html#os_os_networkinterfaces

http://nodejs.org/api/os.html#os_os_networkinterfaces

Best

最好的事物

Edoardo

爱德华多

回答by user123444555621

Here is a snippet of node.js code that will parse the output of ifconfigand (asynchronously) return the first IP address found:

下面是一段 node.js 代码,它将解析输出ifconfig并(异步)返回找到的第一个 IP 地址:

(tested on MacOS Snow Leopard only; hope it works on linux too)

(仅在 MacOS Snow Leopard 上测试;希望它也适用于 linux)

var getNetworkIP = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;    
    var command;
    var filterRE;

    switch (process.platform) {
    // TODO: implement for OSs without ifconfig command
    case 'darwin':
         command = 'ifconfig';
         filterRE = /\binet\s+([^\s]+)/g;
         // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
         break;
    default:
         command = 'ifconfig';
         filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
         // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
         break;
    }

    return function (callback, bypassCache) {
         // get cached value
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }
        // system call
        exec(command, function (error, stdout, sterr) {
            var ips = [];
            // extract IPs
            var matches = stdout.match(filterRE);
            // JS has no lookbehind REs, so we need a trick
            for (var i = 0; i < matches.length; i++) {
                ips.push(matches[i].replace(filterRE, ''));
            }

            // filter BS
            for (var i = 0, l = ips.length; i < l; i++) {
                if (!ignoreRE.test(ips[i])) {
                    //if (!error) {
                        cached = ips[i];
                    //}
                    callback(error, ips[i]);
                    return;
                }
            }
            // nothing found
            callback(error, null);
        });
    };
})();

Usage example:

用法示例:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
}, false);

If the second parameter is true, the function will exec a system call every time; otherwise the cached value is used.

如果第二个参数是true,则函数每次都会执行一次系统调用;否则使用缓存的值。



Updated version

更新后的版本

Returns an array of all local network addresses.

返回所有本地网络地址的数组。

Tested on Ubuntu 11.04 and Windows XP 32

在 Ubuntu 11.04 和 Windows XP 32 上测试

var getNetworkIPs = (function () {
    var ignoreRE = /^(127\.0\.0\.1|::1|fe80(:1)?::1(%.*)?)$/i;

    var exec = require('child_process').exec;
    var cached;
    var command;
    var filterRE;

    switch (process.platform) {
    case 'win32':
    //case 'win64': // TODO: test
        command = 'ipconfig';
        filterRE = /\bIPv[46][^:\r\n]+:\s*([^\s]+)/g;
        break;
    case 'darwin':
        command = 'ifconfig';
        filterRE = /\binet\s+([^\s]+)/g;
        // filterRE = /\binet6\s+([^\s]+)/g; // IPv6
        break;
    default:
        command = 'ifconfig';
        filterRE = /\binet\b[^:]+:\s*([^\s]+)/g;
        // filterRE = /\binet6[^:]+:\s*([^\s]+)/g; // IPv6
        break;
    }

    return function (callback, bypassCache) {
        if (cached && !bypassCache) {
            callback(null, cached);
            return;
        }
        // system call
        exec(command, function (error, stdout, sterr) {
            cached = [];
            var ip;
            var matches = stdout.match(filterRE) || [];
            //if (!error) {
            for (var i = 0; i < matches.length; i++) {
                ip = matches[i].replace(filterRE, '')
                if (!ignoreRE.test(ip)) {
                    cached.push(ip);
                }
            }
            //}
            callback(error, cached);
        });
    };
})();

Usage Example for updated version

更新版本的使用示例

getNetworkIPs(function (error, ip) {
console.log(ip);
if (error) {
    console.log('error:', error);
}
}, false);

回答by jhurliman

Here's my utility method for getting the local IP address, assuming you are looking for an IPv4 address and the machine only has one real network interface. It could easily be refactored to return an array of IPs for multi-interface machines.

这是我获取本地 IP 地址的实用方法,假设您正在寻找 IPv4 地址并且机器只有一个真实的网络接口。它可以很容易地重构为为多接口机器返回一组 IP。

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }

  return '0.0.0.0';
}

回答by Gokul

Install a module called ip like

安装一个名为 ip 的模块

npm install ip

then use this code.

然后使用此代码。

var ip = require("ip");
console.log( ip.address() );

回答by Jimbly

Calling ifconfig is very platform-dependent, and the networking layer does know what ip addresses a socket is on, so best is to ask it. Node doesn't expose a direct method of doing this, but you can open any socket, and ask what local IP address is in use. For example, opening a socket to www.google.com:

调用 ifconfig 非常依赖于平台,网络层确实知道套接字所在的 IP 地址,所以最好询问它。Node 没有公开这样做的直接方法,但您可以打开任何套接字,并询问正在使用的本地 IP 地址。例如,打开一个到 www.google.com 的套接字:

var net = require('net');
function getNetworkIP(callback) {
  var socket = net.createConnection(80, 'www.google.com');
  socket.on('connect', function() {
    callback(undefined, socket.address().address);
    socket.end();
  });
  socket.on('error', function(e) {
    callback(e, 'error');
  });
}

Usage case:

使用案例:

getNetworkIP(function (error, ip) {
    console.log(ip);
    if (error) {
        console.log('error:', error);
    }
});

回答by Tor Valamo

Your local IP is always 127.0.0.1.

您的本地 IP 始终为 127.0.0.1。

Then there is the network IP, which you can get from ifconfig(*nix) or ipconfig(win). This is only useful within the local network.

然后是网络 IP,您可以从ifconfig(*nix) 或ipconfig(win) 获取。这仅在本地网络内有用。

Then there is your external/public IP, which you can only get if you can somehow ask the router for it, or you can setup an external service which returns the client IP address whenever it gets a request. There are also other such services in existence, like whatismyip.com.

然后是您的外部/公共 IP,只有在您可以以某种方式向路由器询问时才能获得该 IP,或者您可以设置一个外部服务,该服务在收到请求时返回客户端 IP 地址。还有其他这样的服务存在,比如 whatismyip.com。

In some cases (for instance if you have a WAN connection) the network IP and the public IP are the same, and can both be used externally to reach your computer.

在某些情况下(例如,如果您有 WAN 连接)网络 IP 和公共 IP 是相同的,并且都可以在外部使用以访问您的计算机。

If your network and public IPs are different, you may need to have your network router forward all incoming connections to your network ip.

如果您的网络和公共 IP 不同,您可能需要让您的网络路由器将所有传入连接转发到您的网络 IP。



Update 2013:

2013 年更新:

There's a new way of doing this now, you can check the socket object of your connection for a property called localAddress, e.g. net.socket.localAddress. It returns the address on your end of the socket.

现在有一种新方法可以做到这一点,您可以检查连接的套接字对象是否有名为 的属性localAddress,例如net.socket.localAddress。它返回套接字末端的地址。

Easiest way is to just open a random port and listen on it, then get your address and close the socket.

最简单的方法是打开一个随机端口并监听它,然后获取您的地址并关闭套接字。



Update 2015:

2015 年更新:

The previous doesn't work anymore.

以前的已经不行了。

回答by KARTHIKEYAN.A

use npm ip module

使用 npm ip 模块

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'