How to determine a user's IP address in node

后端 未结 19 1096
天命终不由人
天命终不由人 2020-11-22 12:46

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


        
19条回答
  •  轮回少年
    2020-11-22 13:19

    I realize this has been answered to death, but here's a modern ES6 version I wrote that follows airbnb-base eslint standards.

    const getIpAddressFromRequest = (request) => {
      let ipAddr = request.connection.remoteAddress;
    
      if (request.headers && request.headers['x-forwarded-for']) {
        [ipAddr] = request.headers['x-forwarded-for'].split(',');
      }
    
      return ipAddr;
    };
    

    The X-Forwarded-For header may contain a comma-separated list of proxy IPs. The order is client,proxy1,proxy2,...,proxyN. In the real world, people implement proxies that may supply whatever they want in this header. If you are behind a load balancer or something, you can at least trust the first IP in the list is at least whatever proxy some request came through.

提交回复
热议问题