我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
很多时候,我发现有多个内部和外部面向接口可用(例如: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;
其他回答
在我看来,这里的一些答案似乎不必要地过于复杂。 这里有一个更好的方法,使用普通的Nodejs。
import os from "os";
const machine = os.networkInterfaces()["Ethernet"].map(item => item.family==="IPv4")
console.log(machine.address) //gives 192.168.x.x or whatever your local address is
参见文档:NodeJS - os模块:networkInterfaces
如果你不想安装依赖,并且正在运行*nix系统,你可以这样做:
hostname -I
你会得到主机的所有地址,你可以在node中使用这个字符串:
const exec = require('child_process').exec;
let cmd = "hostname -I";
exec(cmd, function(error, stdout, stderr)
{
console.log(stdout + error + stderr);
});
是一行代码,你不需要像'os'或'node-ip'这样可能会意外增加代码复杂性的其他库。
hostname -h
也是你的朋友;-)
希望能有所帮助!
下面是前面例子的一个变种。它会小心过滤掉VMware接口等。如果你不传递索引,它会返回所有地址。否则,您可能希望将其默认值设置为0,然后传递null以获取所有值,但您将整理这些。如果想要添加的话,还可以为regex过滤器传入另一个参数。
function getAddress(idx) {
var addresses = [],
interfaces = os.networkInterfaces(),
name, ifaces, iface;
for (name in interfaces) {
if(interfaces.hasOwnProperty(name)){
ifaces = interfaces[name];
if(!/(loopback|vmware|internal)/gi.test(name)){
for (var i = 0; i < ifaces.length; i++) {
iface = ifaces[i];
if (iface.family === 'IPv4' && !iface.internal && iface.address !== '127.0.0.1') {
addresses.push(iface.address);
}
}
}
}
}
// If an index is passed only return it.
if(idx >= 0)
return addresses[idx];
return addresses;
}
调用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);
}
});
公认的答案是异步的。我想要一个同步版本:
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;
推荐文章
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 相当于字符串。jQuery格式
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小