获取node.js应用程序的公共IP地址
是否有任何node.js模块可以用来获取请求的客户端计算机的公共IP地址? 我不是指IPv4或者IPv6,当你访问http://www.whatismyip.com/时,我需要公共IP 。
我已经尝试过req.connection.remoteAddress;
但是它不会返回公共IP。 它必须是公开的,所以我可以根据IP地址find城市。
谢谢 :)
我知道这个老问题,但现在你可以使用http://whatismyipaddress.com/api获取IP。 只需发送请求到bot.whatismyipaddress.com并获得结果。
var http = require('http'); http.get('http://bot.whatismyipaddress.com', function(res){ res.setEncoding('utf8'); res.on('data', function(chunk){ console.log(chunk); }); });
这里有一个名为external-ip的包,可以为你做npm install external-ip
:
var externalip = require('external-ip'); externalip(function (err, ip) { console.log(ip); // => 8.8.8.8 });
(来源: https : //www.npmjs.org/package/external-ip,https : //stackoverflow.com/a/24608249/823548 )
var ip = (req.headers && req.headers['x-forwarded-for']) || req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress);