乐闻世界logo
搜索文章和话题

How to obtain the IP address of the user in Node.js?

1个答案

1

Getting the user's IP address in Node.js is typically achieved by parsing the HTTP headers carried with the user's request. There are two common scenarios: direct requests from the user to the server, and requests through a proxy (such as NGINX or other load balancers). Below, I will explain how to obtain the IP address in each of these scenarios.

1. Direct Requests

When a user directly sends a request to the Node.js server, you can obtain the IP address using the request.connection.remoteAddress property. This is because the connection property of the request object represents the network connection to the client, and remoteAddress stores the client's IP address.

Example Code:

javascript
const http = require('http'); const server = http.createServer((req, res) => { const ip = req.connection.remoteAddress; res.end(`Your IP address is: ${ip}`); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });

2. Requests Through a Proxy

If the user's request is forwarded through a proxy, such as when using NGINX as a reverse proxy, directly using request.connection.remoteAddress may return the proxy server's IP address instead of the user's real IP address. In this case, you can obtain the original request's IP address using the HTTP header X-Forwarded-For.

Example Code:

javascript
const http = require('http'); const server = http.createServer((req, res) => { let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; ip = ip.split(',')[0]; // If there are multiple IP addresses, take the first one res.end(`Your IP address is: ${ip}`); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });

In this example, X-Forwarded-For may contain one or more IP addresses, typically the first IP is the user's real IP. We split the string and take the first entry to ensure obtaining the correct user IP.

Important Notes

When using the X-Forwarded-For header, ensure your network environment is secure and reliable, as HTTP headers can be tampered with. If possible, configure your proxy server to trust only specific source headers.

These are the basic methods for obtaining the user's IP address in Node.js.

2024年8月6日 00:07 回复

你的答案