简体   繁体   中英

Get remote client ip address NodeJS, ExpressJs

I am trying to get client's ip address with Express js, code is as follows:

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);

But every time I am getting localhost ip address not Public ip address , so how can I get public ip address instead of localhost ip address? can anyone help me please ?

Thanks in advance.

Check the last IP of the x-forwarded-for header.

For example, on aws :

the last IP address in the list is the IP address of the client http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM