Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get request’s HTTP headers with Socket.io?

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 …

     */
});
like image 967
bfontaine Avatar asked Nov 26 '12 20:11

bfontaine


People also ask

How do I pass headers in socket IO client?

To set request header when making connection with socket.io client, we can add the extraHeaders option. const socket = io("http://localhost", { extraHeaders: { Authorization: "...", }, });

What are an HTTP request's header lines for?

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.

How do I add HTTP headers?

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.


1 Answers

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

like image 125
ajtrichards Avatar answered Oct 22 '22 12:10

ajtrichards