我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
对上面答案的改进,原因如下:
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地址的实用方法,假设您正在寻找一个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';
}
很多时候,我发现有多个内部和外部面向接口可用(例如:10.0.75.1,172.100.0.1,192.168.2.3),而我真正想要的是外部接口(172.100.0.1)。
如果其他人也有类似的担忧,这里还有一个关于这个问题的看法,希望能有所帮助……
const address = Object.keys(os.networkInterfaces())
// flatten interfaces to an array
.reduce((a, key) => [
...a,
...os.networkInterfaces()[key]
], [])
// non-internal ipv4 addresses only
.filter(iface => iface.family === 'IPv4' && !iface.internal)
// project ipv4 address as a 32-bit number (n)
.map(iface => ({...iface, n: (d => ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]))(iface.address.split('.'))}))
// set a hi-bit on (n) for reserved addresses so they will sort to the bottom
.map(iface => iface.address.startsWith('10.') || iface.address.startsWith('192.') ? {...iface, n: Math.pow(2,32) + iface.n} : iface)
// sort ascending on (n)
.sort((a, b) => a.n - b.n)
[0]||{}.address;
这里有一个简洁的小命令行,它实现了这个功能:
const ni = require('os').networkInterfaces();
Object
.keys(ni)
.map(interf =>
ni[interf].map(o => !o.internal && o.family === 'IPv4' && o.address))
.reduce((a, b) => a.concat(b))
.filter(o => o)
[0];
谷歌在搜索“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
我所知道的就是我想要以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;
}
}
}
}
当然,如果你想要一个不同的数字,你可以改变数字。
推荐文章
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类