本文翻译自:Get local IP address in node.js
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. 我的机器上运行了一个简单的node.js程序,我想获取运行该程序的PC的本地IP地址。 How do I get it with node.js? 如何使用node.js获得它?
#1楼
参考:https://stackoom.com/question/FKKP/在node-js中获取本地IP地址
#2楼
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. 这是我获取本地IP地址的实用方法,假设您要查找的是IPv4地址,并且计算机只有一个真实的网络接口。 It could easily be refactored to return an array of IPs for multi-interface machines. 可以很容易地对其进行重构,以返回用于多接口计算机的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';
}
#3楼
Any IP of your machine you can find by using the os module - and that's native to 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 ifconfig by leagues 您所需要做的就是调用os.networkInterfaces() ,您将获得一个易于管理的列表-比按联盟运行ifconfig更容易
http://nodejs.org/api/os.html#os_os_networkinterfaces http://nodejs.org/api/os.html#os_os_networkinterfaces
Best 最好
Edoardo 爱德华多
#4楼
For anyone interested in brevity, here are some "one-liners" that do not require plugins/dependencies that aren't part of a standard Node installation: 对于任何对简洁感兴趣的人,这里有一些“单行代码”,它们不需要标准Node安装中不包含的插件/依赖项:
Public IPv4 and IPv6 of eth0 as an Array: eth0的公共IPv4和IPv6作为数组:
var ips = require('os').networkInterfaces().eth0.map(function(interface) {
return interface.address;
});
First Public IP of eth0 (usually IPv4) as String: eth0的第一个公共IP(通常为IPv4)作为字符串:
var ip = require('os').networkInterfaces().eth0[0].address;
#5楼
Here is a multi-ip version of jhurliman's answer above: 这是上述jhurliman答案的多IP版本:
function getIPAddresses() {
var ipAddresses = [];
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) {
ipAddresses.push(alias.address);
}
}
}
return ipAddresses;
}
#6楼
https://github.com/indutny/node-ip https://github.com/indutny/node-ip
var ip = require("ip");
console.dir ( ip.address() );