如何从控制器内确定给定请求的IP地址?例如(在快递中):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
如何从控制器内确定给定请求的IP地址?例如(在快递中):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
当前回答
警告:
不要盲目地将其用于重要的速率限制:
let ip = request.headers['x-forwarded-for'].split(',')[0];
这很容易被欺骗:
curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"
在这种情况下,用户的真实IP地址将是:
let ip = request.headers['x-forwarded-for'].split(',')[1];
我很惊讶,没有其他答案提到这一点。
其他回答
在nodejs中简单获取远程ip:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
如果您使用的是快速版3。X或更大,您可以使用信任代理设置(http://expressjs.com/api.html#trust.proxy.options.table),它将遍历X -forward -for报头中的地址链,并将链中尚未配置为受信任代理的最新IP放入req对象的IP属性中。
以下函数涵盖了所有的情况,将会有所帮助
var ip;
if (req.headers['x-forwarded-for']) {
ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
ip = req.connection.remoteAddress;
} else {
ip = req.ip;
}console.log("client IP is *********************" + ip);
我们可以在node js中检查这段代码
const os = require('os');
const interfaces = os.networkInterfaces();
let addresses = [];
for (var k in interfaces) {
for (var k2 in interfaces[k]) {
const address = interfaces[k][k2];
if ( (address.family === 'IPv4' || address.family === 'IPv6') &&
!address.internal) {
addresses.push(address.address);
}
}
}
console.log(addresses);
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
var ip = req.ip
console.log(ip);
res.send('Hello World!')
})
// Run as nodejs ip.js
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})