Issue
So I have a nodejs web socket server sitting behind a nginx reverse proxy. My nginx configuration looks like this:
server {
listen 80;
location / {
proxy_pass http://localhost:9898;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $remote_addr;
}
}
My web socket server application code contains logic that stores the client's IP address in a table for retrieving later. I don't have a problem retrieving the client's IP address when they connect because I can simply do something like this req.headers["x-forwarded-for"]
since I have access to the req
object on every new connection. My problem is retrieving that "forwarded IP address" whenever I want to send out a server broadcast only to a subset of certain clients. Because whenever I do ws._socket.remoteAddress
(where ws
is the web socket object), I expectantly get the IP address: 127.0.0.1
.
I guess this is a question regarding the specific npm package I'm using to host a web socket server: https://www.npmjs.com/package/ws.
Solution
Your question is answered in the NPM page you linked:
When the server runs behind a proxy like NGINX, the de-facto standard is to use the
X-Forwarded-For
header.
wss.on('connection', function connection(ws, req) { const ip = req.headers['x-forwarded-for'].split(/\s*,\s*/)[0]; });
You could store that ip
on the ws
object (and in fact, you can maybe overwrite ws._socket.remoteAddress
with that ip
too) at that point.
Answered By - AKX Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.