1. Get the User IP address using Nodejs native notation
When using the req.connection.remoteAddress acquired IP default is IPv6 address, when we need to get IPv4 address, the wording as follows:
First you need to specify the host as 0.0.0.0, i.e. app.listen(port, 0.0.0.0, () => {}) ;
Use the following methods where you need to obtain the IP:
//传入请求HttpRequestfunction getClientIp(req) { return req.headers[‘x-forwarded-for‘] || // 判断是否有反向代理 IP req.connection.remoteAddress || // 判断 connection 的远程 IP req.socket.remoteAddress || // 判断后端的 socket 的 IP req.connection.socket.remoteAddress;}
2. Use Express Scaffolding project to get the user IP address
First, you also need to specify host 0.0.0.0, locate the WWW file under the Bin folder, and server.listen(port) change the revision toserver.listen(port, 0.0.0.0)
Using the express framework to get IP is much simpler, as follows:
//express框架获取ipfunction getClientIp(req) { return req.ip}
Nodejs getting the client IP address