如何在节点中确定用户的IP地址 [英] How to determine a user's IP address in node

查看:32
本文介绍了如何在节点中确定用户的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在你的 request 对象有一个属性叫做 socket,这是一个 net.Socket 对象.net.Socket 对象有一个属性 remoteAddress,因此您应该能够通过此调用获取 IP:

In your request object there is a property called socket, 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.socket.remoteAddress

(如果您的节点版本低于 13,请使用现已弃用的<代码>request.connection.remoteAddress)

(if your node version is below 13, use the deprecated now request.connection.remoteAddress)

编辑

正如@juand 在评论中指出的,获取远程 IP 的正确方法是 request.headers['x-forwarded-for']

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

这篇关于如何在节点中确定用户的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆