我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?
当前回答
我可能在这个问题上迟到了,但如果有人想要一个一行ES6解决方案来获得IP地址数组,那么这应该会帮助你:
Object.values(require("os").networkInterfaces())
.flat()
.filter(({ family, internal }) => family === "IPv4" && !internal)
.map(({ address }) => address)
As
Object.values(require("os").networkInterfaces())
将返回一个数组的数组,所以flat()是用来将其平展为单个数组
.filter(({ family, internal }) => family === "IPv4" && !internal)
将过滤数组只包括IPv4地址,如果它不是内部
最后
.map(({ address }) => address)
是否只返回过滤数组的IPv4地址
所以结果是['192.168.xx。xx ']
然后,如果您想要或更改筛选条件,您可以获得该数组的第一个索引
操作系统为Windows
其他回答
您的本地IP地址总是127.0.0.1。
然后是网络IP地址,可以从ifconfig (*nix)或ipconfig (win)中获取。这只在本地网络中有用。
然后是你的外部/公共IP地址,你只能通过某种方式向路由器请求它,或者你可以设置一个外部服务,在收到请求时返回客户端IP地址。还有其他类似的服务,比如whatismyip.com。
在某些情况下(例如,如果您有一个广域网连接),网络IP地址和公共IP地址是相同的,并且都可以用于外部访问您的计算机。
如果您的网络和公共IP地址不同,您可能需要让网络路由器将所有传入连接转发到您的网络IP地址。
2013年更新:
现在有了一种新的方法。你可以检查连接的套接字对象的localAddress属性,例如net.socket.localAddress。它返回套接字一端的地址。
最简单的方法是打开一个随机端口并监听它,然后获取您的地址并关闭套接字。
2015年更新:
前面的已经不管用了。
对于Linux和macOS,如果你想通过同步方式获取你的IP地址,试试这个:
var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);
结果会是这样的:
['192.168.3.2', '192.168.2.1']
类似于其他答案,但更简洁:
'use strict';
const interfaces = require('os').networkInterfaces();
const addresses = Object.keys(interfaces)
.reduce((results, name) => results.concat(interfaces[name]), [])
.filter((iface) => iface.family === 'IPv4' && !iface.internal)
.map((iface) => iface.address);
下面的解决方案对我来说是可行的
const ip = Object.values(require("os").networkInterfaces())
.flat()
.filter((item) => !item.internal && item.family === "IPv4")
.find(Boolean).address;
很多时候,我发现有多个内部和外部面向接口可用(例如: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;