如何从控制器内确定给定请求的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
})
当前回答
如果你有多个ip,这对我来说是可行的:
Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];
其他回答
在你的请求对象中有一个属性叫socket,它是一个网络。套接字对象。净。套接字对象有一个属性remoteAddress,因此你应该能够通过这个调用得到IP:
request.socket.remoteAddress
(如果您的节点版本低于13,请使用已弃用的request.connection.remoteAddress)
EDIT
正如@juand在评论中指出的那样,如果服务器位于代理之后,获得远程IP的正确方法是request.headers['x-forwarded-for']
编辑2
在Node.js中使用express时:
如果你设置了app.set('信任代理',true),请请求。ip将返回真实ip地址,即使在代理。查看文档了解更多信息
函数getCallerIP(请求){ Var IP = request。标题(“x-forwarded-for”)| | request.connection.remoteAddress | | request.socket.remoteAddress | | request.connection.socket.remoteAddress; IP = IP .split(',')[0]; IP = IP .split(':').slice(-1);//如果IP以“::ffff:146.xxx.xxx.xxx”格式返回 返回的ip; }
我知道这个问题已经被回答了,但下面是我写的一个现代ES6版本,它遵循airbnb的eslint标准。
const getIpAddressFromRequest = (request) => {
let ipAddr = request.connection.remoteAddress;
if (request.headers && request.headers['x-forwarded-for']) {
[ipAddr] = request.headers['x-forwarded-for'].split(',');
}
return ipAddr;
};
X-Forwarded-For报头可以包含以逗号分隔的代理ip列表。订单是client,proxy1,proxy2,…,proxyN。在现实世界中,人们实现的代理可以在这个报头中提供他们想要的任何东西。如果你是负载均衡器之类的,你至少可以相信列表中的第一个IP至少是某个请求通过的代理。
对于我使用kubernetes ingress (NGINX):
req.headers['x-original-forwarded-for']
在Node.js中非常有效
请求。headers['x-forwarded-for'] || request.connection.remoteAddress . headers['x-forwarded-for'
如果有x-forward -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 the 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.