How to determine a user's IP address in node

2018-12-31 18:18发布

问题:

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

回答1:

In your request object there is a property called connection, which is a net.Socket object. The net.Socket object has a property remoteAddress, therefore you should be able to get the IP with this call:

request.connection.remoteAddress

See documentation for http and net

EDIT

As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers[\'x-forwarded-for\']



回答2:

var ip = req.headers[\'x-forwarded-for\'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);

Note that sometimes you can get more than one IP address in req.headers[\'x-forwarded-for\']. Also, an x-forwarded-for header will not always be set which may throw an error.

The general format of the field is:

x-forwarded-for: client, proxy1, proxy2, proxy3

where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1, proxy2, and then proxy3. proxy3 appears as remote address of the request.

This is the solution suggested by Arnav Gupta with a fix Martin has suggested below in the comments for cases when x-forwarded-for is not set :

var ip = (req.headers[\'x-forwarded-for\'] || \'\').split(\',\').pop() || 
         req.connection.remoteAddress || 
         req.socket.remoteAddress || 
         req.connection.socket.remoteAddress


回答3:

You can stay DRY and just use node-ipware that supports both IPv4 and IPv6.

Install:

npm install ipware

In your app.js or middleware:

var getIP = require(\'ipware\')().get_ip;
app.use(function(req, res, next) {
    var ipInfo = getIP(req);
    console.log(ipInfo);
    // { clientIp: \'127.0.0.1\', clientIpRoutable: false }
    next();
});

It will make the best attempt to get the user\'s IP address or returns 127.0.0.1 to indicate that it could not determine the user\'s IP address. Take a look at the README file for advanced options.



回答4:

If using express...

req.ip

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



回答5:

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



回答6:

Following Function has all the cases covered will help

var ip;
if (req.headers[\'x-forwarded-for\']) {
    ip = req.headers[\'x-forwarded-for\'].split(\",\")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}console.log(\"client IP is *********************\" + ip);


回答7:

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 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.



回答8:

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.



回答9:

function getCallerIP(request) {
    var ip = request.headers[\'x-forwarded-for\'] ||
        request.connection.remoteAddress ||
        request.socket.remoteAddress ||
        request.connection.socket.remoteAddress;
    ip = ip.split(\',\')[0];
    ip = ip.split(\':\').slice(-1); //in case the ip returned in a format: \"::ffff:146.xxx.xxx.xxx\"
    return ip;
}



回答10:

There are two ways to get the ip address :

  1. let ip = req.ip

  2. let ip = req.connection.remoteAddress;

But there is a problem with above approaches.

If you are running your app behind Nginx or any proxy, every single IP addresses will be 127.0.0.1.

So, the best solution to get the ip address of user is :-

let ip = req.header(\'x-forwarded-for\') || req.connection.remoteAddress;


回答11:

Simple get remote ip in nodejs:

var ip = req.header(\'x-forwarded-for\') || req.connection.remoteAddress;


回答12:

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



回答13:

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.



回答14:

In node 10.14 , behind nginx, you can retrieve the ip by requesting it through nginx header like this:

proxy_set_header X-Real-IP $remote_addr;

Then in your app.js:

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

After that, wherever you want it to appear:

var userIp = req.header(\'X-Real-IP\') || req.connection.remoteAddress;


回答15:

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


标签: api node.js ip