如何从控制器中确定给定请求的IP地址?例如(快递):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
Run Code Online (Sandbox Code Playgroud)
top*_*pek 418
在您的request对象中有一个名为的属性connection,它是一个net.Socket对象.net.Socket对象有一个属性remoteAddress,因此您应该能够通过此调用获取IP:
request.connection.remoteAddress
Run Code Online (Sandbox Code Playgroud)
编辑
正如@juand在评论中指出的那样,如果服务器位于代理之后,获取远程IP的正确方法是 request.headers['x-forwarded-for']
Edm*_*ake 379
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
Run Code Online (Sandbox Code Playgroud)
请注意,有时您可以获得多个IP地址req.headers['x-forwarded-for'].此外,x-forwarded-for不会始终设置标头,这可能会引发错误.
该领域的一般格式是:
的x转发换: client, proxy1, proxy2, proxy3
其中值是逗号+空格分隔的IP地址列表,最左边是原始客户端,每个连续的代理通过请求添加接收请求的IP地址.在此示例中,请求通过proxy1,proxy2然后传递proxy3.proxy3显示为请求的远程地址.
这是Arnav Gupta建议的解决方案,马丁在下面的评论中为x-forwarded-for未设置的案例提出了修正:
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop() ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress
Run Code Online (Sandbox Code Playgroud)
Jas*_*ing 69
我正在看这个,然后我就像等待,我正在使用快递.咄.
un3*_*33k 29
您可以保持DRY并且只使用支持IPv4和IPv6的node-ipware.
安装:
npm install ipware
Run Code Online (Sandbox Code Playgroud)
在您的app.js或中间件中:
var getIP = require('ipware')().get_ip;
app.use(function(req, res, next) {
var ipInfo = getIP(req);
console.log(ipInfo);
// { clientIp: '127.0.0.1', clientIpRoutable: false }
next();
});
Run Code Online (Sandbox Code Playgroud)
它将尽最大努力获取用户的IP地址或返回127.0.0.1以指示它无法确定用户的IP地址.查看README文件以获取高级选项.
pbo*_*nov 18
您可以使用request-ip来检索用户的IP地址.它处理了相当多的不同边缘情况,其中一些在其他答案中提到.
披露:我创建了这个模块
安装:
npm install request-ip
Run Code Online (Sandbox Code Playgroud)
在您的应用中:
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();
};
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
Ben*_*ies 17
request.headers['x-forwarded-for'] || request.connection.remoteAddress
如果x-forwarded-for标题在那里然后使用它,否则使用该.remoteAddress属性.
The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress property will contain the private ip address of the load balancer rather than the public ip address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.
ash*_*e11 12
以下函数已涵盖所有案例将有所帮助
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);
Run Code Online (Sandbox Code Playgroud)
function getCallerIP(request) {
var ip = request.headers['x-forwarded-for'] ||
request.connection.remoteAddress ||
request.socket.remoteAddress ||
request.connection.socket.remoteAddress;
ip = ip.split(',')[0];
ip = ip.split(':').slice(-1); //in case the ip returned in a format: "::ffff:146.xxx.xxx.xxx"
return ip;
}Run Code Online (Sandbox Code Playgroud)
小智 7
获取IP地址有两种方法:
let ip = req.ip
let ip = req.connection.remoteAddress;
但是上述方法存在问题.
如果您在Nginx或任何代理后面运行您的应用程序,则每个IP地址都将是127.0.0.1.
因此,获取用户IP地址的最佳解决方案是: -
let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
Run Code Online (Sandbox Code Playgroud)
小智 7
在节点 10.14 中,在 nginx 后面,您可以通过像这样通过 nginx 标头请求来检索 ip:
proxy_set_header X-Real-IP $remote_addr;
Run Code Online (Sandbox Code Playgroud)
然后在你的 app.js 中:
app.set('trust proxy', true);
Run Code Online (Sandbox Code Playgroud)
之后,无论您希望它出现在何处:
var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;
Run Code Online (Sandbox Code Playgroud)
小智 7
Don't just blindly use this for important rate-limiting:
let ip = request.headers['x-forwarded-for'].split(',')[0];
Run Code Online (Sandbox Code Playgroud)
It's very easy to spoof:
curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"
Run Code Online (Sandbox Code Playgroud)
In that case ther user's real IP address will be:
let ip = request.headers['x-forwarded-for'].split(',')[1];
Run Code Online (Sandbox Code Playgroud)
我很惊讶没有其他答案提到这一点。
如果您使用的是快速版本3.x或更高版本,则可以使用信任代理设置(http://expressjs.com/api.html#trust.proxy.options.table),它将遍历地址链x-forwarded-for标头并将最新的ip放入您未配置为可信代理的链中,放入req对象的ip属性中.
我已经尝试了所有这些都不起作用,
console.log(clientIp);
console.log(req.ip);
console.log(req.headers['x-forwarded-for']);
console.log(req.connection.remoteAddress);
console.log(req.socket.remoteAddress);
console.log(req.connection.socket.remoteAddress.split(",")[0]);
Run Code Online (Sandbox Code Playgroud)
在 Nginx 代理后面运行 Express 应用程序时,您必须将应用程序变量 trust proxy 设置为 true。Express 提供了一些其他信任代理值,您可以在他们的文档中查看这些值,但以下步骤对我有用。
app.set('trust proxy', true);
Run Code Online (Sandbox Code Playgroud)location / { proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; # this line proxy_cache_bypass $http_upgrade; }
Run Code Online (Sandbox Code Playgroud)module.exports = function(req, res, next) { let enable = true; // true/false let blacklist = ['x.x.x.x']; let whitelist = ['x.x.x.x']; let clientIp = req.header('x-forwarded-for') || req.connection.remoteAddress; if (!clientIp) { return res.json('Error'); } if (enable && paths.some((path) => (path === req.originalUrl))) { let blacklist = blacklist || []; if (blacklist.some((ip) => clientIp.match(ip) !== null)) { return res.json({ status: 401, error: 'Your IP is black-listed !'}); } let whitelist = whitelist || []; if (whitelist.length === 0 || whitelist.some((ip) => clientIp.match(ip) !== null)) { next(); return; } else { return res.json({ status: 401, error: 'Your IP is not listed !'}); } } next(); };
小智 5
如果你使用的是express.js,
app.post('/get/ip/address', function (req, res) {
res.send(req.ip);
})
Run Code Online (Sandbox Code Playgroud)
小智 5
var ipaddress = (req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress).split(",")[0];Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
306883 次 |
| 最近记录: |