How to determine a user's IP address in node

2018-12-31 18:10发布

How can I determine the IP address of a given request from within a controller? For example (in express):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

标签: api node.js ip
15条回答
君临天下
2楼-- · 2018-12-31 19:10

Had the same problem...im also new at javascript but i solved this with req.connection.remoteAddress; that gave me th IP address (but in ipv6 format ::ffff.192.168.0.101 ) and then .slice to remove the 7 first digits.

var ip = req.connection.remoteAddress;

if (ip.length < 15) 
{   
   ip = ip;
}
else
{
   var nyIP = ip.slice(7);
   ip = nyIP;
}
查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 19:10

If using express...

req.ip

I was looking this up then I was like wait, I'm using express. Duh.

查看更多
裙下三千臣
4楼-- · 2018-12-31 19:13

If you get multiple IPs , this works for me:

var ipaddress = (req.headers['x-forwarded-for'] || 
req.connection.remoteAddress || 
req.socket.remoteAddress || 
req.connection.socket.remoteAddress).split(",")[0];

查看更多
登录 后发表回答