node.js 如何在节点中确定用户的IP地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8107856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:45:31  来源:igfitidea点击:

How to determine a user's IP address in node

apinode.jsip

提问by Shamoon

How can I determine the IP address of a given request from within a controller? For example (in express):

如何从控制器中确定给定请求的 IP 地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

回答by topek

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

在您的request对象中有一个名为 的属性connection,它是一个net.Socket对象。net.Socket 对象有一个属性remoteAddress,因此您应该能够通过此调用获取 IP:

request.connection.remoteAddress

See documentation for httpand net

请参阅httpnet 的文档

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

正如@juand 在评论中指出的那样,如果服务器位于代理后面,则获取远程 IP 的正确方法是 request.headers['x-forwarded-for']

回答by Edmar Miyake

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-forheader will not always be set which may throw an error.

请注意,有时您可以在req.headers['x-forwarded-for']. 此外,x-forwarded-for不会总是设置可能引发错误的标头。

The general format of the field is:

该字段的一般格式为:

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

x 转发: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. proxy3appears as remote address of the request.

其中该值是一个逗号+空格分隔的 IP 地址列表,最左边是原始客户端,每个后续的通过请求的代理都添加了从其接收请求的 IP 地址。在此示例中,请求通过proxy1proxy2,然后proxy3proxy3显示为请求的远程地址。

This is the solution suggested by Arnav Guptawith a fix Martinhas suggested below in the comments for cases when x-forwarded-foris not set :

这是Arnav Gupta建议的解决方案,其中Martin在以下评论中针对x-forwarded-for未设置的情况提出了修复建议:

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

回答by Jason Sebring

If using express...

如果使用快递...

req.ip

req.ip

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

我正在查找这个然后我就像等待,我正在使用快递。呃。

回答by un33k

You can stay DRYand just use node-ipwarethat supports both IPv4and IPv6.

您可以保持DRY并只使用支持IPv4IPv6 的node-ipware

Install:

安装:

npm install ipware

In your app.js or middleware:

在您的 app.js 或中间件中:

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.1to indicate that it could not determine the user's IP address. Take a look at the READMEfile for advanced options.

它将尽最大努力获取用户的 IP 地址或返回127.0.0.1表示无法确定用户的 IP 地址。查看README文件了解高级选项。

回答by pbojinov

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.

您可以使用request-ip来检索用户的 IP 地址。它处理了很多不同的边缘情况,其中一些在其他答案中提到过。

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

希望这可以帮助

回答by Ben Davies

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

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

If the x-forwarded-forheader is there then use that, otherwise use the .remoteAddressproperty.

如果x-forwarded-for标题在那里,则使用该标题,否则使用该.remoteAddress属性。

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

x-forwarded-for标头被添加到通过为HTTPHTTPS设置的负载平衡器(或其他类型的代理)的请求中(当使用代理协议TCP级别进行平衡时,也可以将此标头添加到请求中)。这是因为该属性将包含负载均衡器的私有 IP 地址,而不是客户端的公共 IP 地址。通过使用OR语句,按照上述顺序,您可以检查标头是否存在,如果存在则使用它,否则使用.request.connection.remoteAddressx-forwarded-forrequest.connection.remoteAddress

回答by ashishyadaveee11

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

回答by Mansi Teharia

There are two ways to get the ip address :

获取ip地址有两种方式:

  1. let ip = req.ip

  2. let ip = req.connection.remoteAddress;

  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.

如果您在 Nginx 或任何代理之后运行您的应用程序,则每个 IP 地址都将是127.0.0.1.

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

因此,获取用户 IP 地址的最佳解决方案是:-

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

回答by Ahmad Agbaryah

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

回答by Michael Lang

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.

如果您使用的是 express 3.x 或更高版本,则可以使用信任代理设置 ( http://expressjs.com/api.html#trust.proxy.options.table),它将遍历地址链x-forwarded-for 标头并将链中未配置为受信任代理的最新 ip 放入 req 对象的 ip 属性中。