I have an Express app running behind Nginx, so when I try to get the user’s IP, I always get 127.0.0.1
instead of the real one, which is set by Nginx in the X-Real-IP
header. How do I get this header? Is there a way to have it via the socket
object?
The code would be basically like that:
io.sockets.on( 'connection', function( socket ) {
var ip = /* ??? */;
/* do something with the IP…
… some stuff …
*/
});
To set request header when making connection with socket.io client, we can add the extraHeaders option. const socket = io("http://localhost", { extraHeaders: { Authorization: "...", }, });
HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon ( : ), then by its value. Whitespace before the value is ignored.
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
To get the IP when you're running behind NGINX or another proxy:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
or for Socket.IO
client.handshake.headers['x-forwarded-for'] || client.handshake.address.address;
From: http://www.hacksparrow.com/node-js-get-ip-address.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With