我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
对于Underscore.js和Lodash,正确的一行代码是:
var ip = require('underscore')
.chain(require('os').networkInterfaces())
.values()
.flatten()
.find({family: 'IPv4', internal: false})
.value()
.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);
安装一个名为ip的模块,如下:
npm install ip
然后使用下面的代码:
var ip = require("ip");
console.log(ip.address());
一行程序只用于macOS的第一个本地主机地址。
当在macOS上开发应用程序时,你想在手机上测试它,并且需要你的应用程序自动选择本地主机IP地址。
require('os').networkInterfaces().en0.find(elm => elm.family=='IPv4').address
这只是提到如何自动查找ip地址。 要测试这个,你可以去终端点击
node
os.networkInterfaces().en0.find(elm => elm.family=='IPv4').address
输出将是您的本地主机IP地址。
使用内部ip:
const internalIp = require("internal-ip")
console.log(internalIp.v4.sync())
我只用Node.js就能做到这一点。
node . js:
var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
.reduce((r,a) => {
r = r.concat(a)
return r;
}, [])
.filter(({family, address}) => {
return family.toLowerCase().indexOf('v4') >= 0 &&
address !== '127.0.0.1'
})
.map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);
作为Bash脚本(需要安装Node.js)
function ifconfig2 ()
{
node -e """
var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
.reduce((r,a)=>{
r = r.concat(a)
return r;
}, [])
.filter(({family, address}) => {
return family.toLowerCase().indexOf('v4') >= 0 &&
address !== '127.0.0.1'
})
.map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);
"""
}
推荐文章
- 给一个数字加上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添加必要的输入字段