0

我正在尝试使用 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 address 而不是Public ip address,那么我怎样才能得到 public ip address 而不是 localhost ip address 呢?谁能帮帮我?

提前致谢。

4

1 回答 1

2

检查x-forwarded-for标头的最后一个 IP。

例如,在 aws 上:

列表中最后一个 IP 地址是客户端的 IP 地址 http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-for

于 2017-11-17T10:06:36.363 回答