How to determine a user's IP address in node

后端 未结 19 884
天命终不由人
天命终不由人 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:07

    request.headers['x-forwarded-for'] || request.connection.remoteAddress

    If the x-forwarded-for header is there then use that, otherwise use the .remoteAddress property.

    The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress the property will contain the private IP address of the load balancer rather than the public IP address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.

    0 讨论(0)
  • 2020-11-22 13:08

    You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.

    Disclosure: I created this module

    Install:

    npm install request-ip
    

    In your app:

    var requestIp = require('request-ip');
    
    // inside middleware handler
    var ipMiddleware = function(req, res, next) {
        var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
        next();
    };
    

    Hope this helps

    0 讨论(0)
  • 2020-11-22 13:10

    If you're using express version 3.x or greater, you can use the trust proxy setting (http://expressjs.com/api.html#trust.proxy.options.table) and it will walk the chain of addresses in the x-forwarded-for header and put the latest ip in the chain that you've not configured as a trusted proxy into the ip property on the req object.

    0 讨论(0)
  • 2020-11-22 13:11

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

    0 讨论(0)
  • 2020-11-22 13:11

    I'm using express behind nginx and

    req.headers.origin
    

    did the trick for me

    0 讨论(0)
  • 2020-11-22 13:12

    I have tried all of them didn't work though,

    console.log(clientIp);
    console.log(req.ip);
    
    console.log(req.headers['x-forwarded-for']);
    console.log(req.connection.remoteAddress);
    console.log(req.socket.remoteAddress);
    console.log(req.connection.socket.remoteAddress.split(",")[0]);
    

    When running an Express app behind a proxy for me Nginx, you have to set the application variable trust proxy to true. Express offers a few other trust proxy values which you can review in their documentation, but below steps worked for me.

    1. app.set('trust proxy', true) in your Express app.

    app.set('trust proxy', true);

    1. Add proxy_set_header X-Forwarded-For $remote_addr in the Nginx configuration for your server block.
      location /  {
                    proxy_pass    http://localhost:3001;
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection 'upgrade';
                    proxy_set_header Host $host;
                    proxy_set_header X-Forwarded-For $remote_addr;  # this line
                    proxy_cache_bypass $http_upgrade; 
            }
    
    1. You can now read off the client’s IP address from the req.header('x-forwarded-for') or req.connection.remoteAddress; Full code for ipfilter
    module.exports =  function(req, res, next) {
        let enable = true; // true/false
        let blacklist = ['x.x.x.x'];
        let whitelist = ['x.x.x.x'];
        let clientIp = req.header('x-forwarded-for') || req.connection.remoteAddress;
        if (!clientIp) {
            return res.json('Error');
        }
        if (enable
            && paths.some((path) => (path === req.originalUrl))) {
    
            let blacklist = blacklist || [];
            if (blacklist.some((ip) => clientIp.match(ip) !== null)) {
                return res.json({ status: 401, error: 'Your IP is black-listed !'});
            }
            let whitelist = whitelist || [];
            if (whitelist.length === 0 || whitelist.some((ip) => clientIp.match(ip) !== null)) {
                next();
                return;
            } else {
                return res.json({ status: 401, error: 'Your IP is not listed !'});
            }
        }
        next();
    };
    
    0 讨论(0)
提交回复
热议问题