如何从控制器内确定给定请求的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];
我很惊讶,没有其他答案提到这一点。
其他回答
我知道这个问题已经被回答了,但下面是我写的一个现代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至少是某个请求通过的代理。
请求。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.
这里有很多很棒的观点,但没有一个是全面的,所以这里是我最终使用的:
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
}
我使用这个ipv4格式
req.connection.remoteAddress.split(':').slice(-1)[0]
Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];