我试图用Express js获取客户端的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;
}
ip = (ip.length < 15 ? ip : (ip.substr(0, 7) === '::ffff:' ? ip.substr(7) : undefined));
console.log('ip address',ip);
但每次我获取localhost ip地址不是公共IP地址, 那么如何获取公共IP地址而不是localhost ip地址? 有人可以帮我吗?
提前致谢。
答案 0 :(得分:2)
检查x-forwarded-for
标题的最后一个IP。
例如,在aws:
列表中的最后一个IP地址是客户端的IP地址 http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-for