How to find out the remote Address in node.js if i

2019-03-16 14:26发布

HI. in node.js, if it is http request, I can get the remoteAddress at req.connection.remoteAddress,

so, how to get it if https request? I find there is req.socket.remoteAddress but I'm not sure. Please advice. thanks.

标签: https node.js ip
4条回答
冷血范
2楼-- · 2019-03-16 14:41
var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress;

Note that sometimes you can get more than one ip address in req.headers['x-forwarded-for'], specially when working with mobile phones accessing your server (wifi and carrier data).

查看更多
地球回转人心会变
3楼-- · 2019-03-16 14:47

As well req.headers['x-forwarded-for'] is easily manipulated so you need a properly configured proxy server.

Is better to check req.connection.remoteAddress against a list of known proxy servers before to go with req.headers['x-forwarded-for'].

查看更多
看我几分像从前
4楼-- · 2019-03-16 15:00

It appears something is strange/broken indeed. As of node 0.4.7, it seems http has remoteAddress available on:

  • req.connection.remoteAddress
  • req.socket.remoteAddress

on https, both of these are undefined, but

  • req.connection.socket.remoteAddress

does work. That one isn't available on http though, so you need to check carefully. I cannot imagine this behavior is intentional.

查看更多
叛逆
5楼-- · 2019-03-16 15:02

Since googling "express js ip" directly points to here, this is somehow relevant.

Express 3.0.0 alpha now offers a new way of retrieving IP adresses for client requests. Simply use req.ip. If you're doing some proxy jiggery-pokery you might be interested in app.set("trust proxy", true); and req.ips.

I recommend you to read the whole discussion in the Express Google Group.

查看更多
登录 后发表回答