如何从控制器内确定给定请求的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
})
当前回答
如果使用express…
req.ip
我在查这个,然后我想,等等,我用的是快递。咄。
其他回答
你可以使用request-ip来获取用户的ip地址。它处理了很多不同的边界情况,其中一些在其他答案中提到过。
披露:我创建了这个模块
安装:
npm install request-ip
在你的应用中:
var requestIp = require('request-ip');
// inside middleware handler
var ipMiddleware = function(req, res, next) {
var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
next();
};
希望这能有所帮助
这里有很多很棒的观点,但没有一个是全面的,所以这里是我最终使用的:
function getIP(req) {
// req.connection is deprecated
const conRemoteAddress = req.connection?.remoteAddress
// req.socket is said to replace req.connection
const sockRemoteAddress = req.socket?.remoteAddress
// some platforms use x-real-ip
const xRealIP = req.headers['x-real-ip']
// most proxies use x-forwarded-for
const xForwardedForIP = (() => {
const xForwardedFor = req.headers['x-forwarded-for']
if (xForwardedFor) {
// The x-forwarded-for header can contain a comma-separated list of
// IP's. Further, some are comma separated with spaces, so whitespace is trimmed.
const ips = xForwardedFor.split(',').map(ip => ip.trim())
return ips[0]
}
})()
// prefer x-forwarded-for and fallback to the others
return xForwardedForIP || xRealIP || sockRemoteAddress || conRemoteAddress
}
以下函数涵盖了所有的情况,将会有所帮助
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);
警告:
不要盲目地将其用于重要的速率限制:
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];
我很惊讶,没有其他答案提到这一点。
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}`)
})