Node.js: Get client's IP

前端 未结 5 1678
我在风中等你
我在风中等你 2020-12-03 01:13

req.connection.remoteAddress, req.headers[\'x-forwarded-for\'], req.ip, req.ips, what does it all mean?

Is there a straight forward way to simply get the IP address

相关标签:
5条回答
  • 2020-12-03 01:28
    // Get client IP address from request object ----------------------
    getClientAddress = function (req) {
            return (req.headers['x-forwarded-for'] || '').split(',')[0] 
            || req.connection.remoteAddress;
    };
    
    0 讨论(0)
  • 2020-12-03 01:40

    very simple

    function getClientIP(req){
        return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    }
    
    0 讨论(0)
  • 2020-12-03 01:41

    req.ip is the straightforward way to get the client's IP address in Express. You can see the logic it uses (which involves grabbing the first item from the array of proxy addresses req.ips, where that array is constructed from the x-forwarded-for headers) here.

    0 讨论(0)
  • 2020-12-03 01:43

    Getting the client IP is pretty straightforward:

     var ip = req.headers['x-forwarded-for'] || 
         req.connection.remoteAddress || 
         req.socket.remoteAddress ||
         req.connection.socket.remoteAddress;
         console.log(ip);
    
    0 讨论(0)
  • 2020-12-03 01:46

    As other's have noted, due to the use potential use of proxies, you really should use req.ip and NOT use the X-Forwarded-For header like so many people are recommending. As long as you properly configure a proxy as a trusted proxy, req.ip will always return the end-user's IP address.

    e.g. If you had a proxy that was connecting from 8.8.8.8, you'd do:

    var express = require('express');
    var app = express();
    app.set('trust proxy', '8.8.8.8');
    

    Since you trust the proxy, this would now make it so what is passed in the X-Forwarded-For header will be stored in req.ip, but ONLY if it originates from one of the trusted proxies.

    More on trust proxy can be found here.

    Now, as others have noted in the comments; especially when developing locally you may get the ip in the format of "::ffff:127.0.0.1".

    To always get the IPv4 Address I have:

    getClientAddress = function (req) {
            return req.ip.split(":").pop();
    };
    
    0 讨论(0)
提交回复
热议问题