我有一个简单的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;
}
}
}
}
当然,如果你想要一个不同的数字,你可以改变数字。
其他回答
对上面答案的改进,原因如下:
Code should be as self-explanatory as possible. Enumerating over an array using for...in... should be avoided. for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available. var os = require('os'), interfaces = os.networkInterfaces(), address, addresses = [], i, l, interfaceId, interfaceArray; for (interfaceId in interfaces) { if (interfaces.hasOwnProperty(interfaceId)) { interfaceArray = interfaces[interfaceId]; l = interfaceArray.length; for (i = 0; i < l; i += 1) { address = interfaceArray[i]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } } console.log(addresses);
根据注释,以下是当前版本Node.js的工作原理:
var os = require('os');
var _ = require('lodash');
var ip = _.chain(os.networkInterfaces())
.values()
.flatten()
.filter(function(val) {
return (val.family == 'IPv4' && val.internal == false)
})
.pluck('address')
.first()
.value();
上面一个答案的注释缺少对values()的调用。看起来os.networkInterfaces()现在返回一个对象而不是数组。
调用ifconfig是非常依赖于平台的,而且网络层知道套接字所在的IP地址,所以最好是询问它。
Node.js并没有公开这样做的直接方法,但是你可以打开任何套接字,并询问正在使用的本地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');
});
}
使用情况:
getNetworkIP(function (error, ip) {
console.log(ip);
if (error) {
console.log('error:', error);
}
});
下面是一个允许你获取本地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
公认的答案是异步的。我想要一个同步版本:
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;
推荐文章
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError:
- [].slice的解释。调用javascript?
- jQuery日期/时间选择器
- 我如何预填充一个jQuery Datepicker文本框与今天的日期?
- npm犯错!代码UNABLE_TO_GET_ISSUER_CERT_LOCALLY
- 数组的indexOf函数和findIndex函数的区别
- jQuery添加必要的输入字段