Ws: Client Ip address

Created on 31 May 2017  路  3Comments  路  Source: websockets/ws

Not sure if this qualifies as an '"Issue", but more of a question (there should a forum for such a popular suite).

Being new to web programming pardon my ignorance, but I write this down after spending a couple days in attempt towards resolution.

My setup has a nginx server configured as a reverse proxy redirecting websocket clients.
The server script is as given in the documentation here.

The server and application seem to be setup properly as i can send data to and fro from the local as well as other clients in the LAN.

However,when trying to get the IP address of the client I always end up in an "undefined" using the suggested script for retrieving client IP when running behind a proxy, documented here.

EDIT: on using the script (in the same section) to retrieve the client IP from raw socket, I get results as

::ffff:127.0.0.1

My server script, which is a little tweaked version of the linked script looks like this

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8010 });

// Broadcast to all.
wss.broadcast = function broadcast(data) {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    console.log(client);
    }
  });
};

wss.on('connection', function connection(ws,req) {
  console.log('New client connected from IP');
    const ip = req.headers['x-forwarded-for'];
    console.log(ip);
  ws.on('message', function incoming(data) {
    // Broadcast to everyone else.
    console.log(data);


    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        console.log('Sending..');
    console.log(data);
    console.log(client.remoteAddress);
    client.send(data);

      }
    });
  });
});

The client side files are
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>WebSockets Demo</title>

    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="page-wrapper">
        <h1>WebSockets Demo</h1>

        <div id="status">Connecting...</div>

        <ul id="messages"></ul>

        <form id="message-form" action="#" method="post">
            <textarea id="message" placeholder="Write your message here..." required></textarea>
            <button type="submit">Send Message</button>
            <button type="button" id="close">Close Connection</button>
        </form>
    </div>

    <script src="app.js"></script>
</body>
</html>

and app.js

window.onload = function() {
//alert('sadsads');

//const WebSocket = require('/usr/local/lib/ws');
//alert('sdfsdfdsfdhgdhgfhfg');
  // Get references to elements on the page.
  var form = document.getElementById('message-form');
  var messageField = document.getElementById('message');
  var messagesList = document.getElementById('messages');
  var socketStatus = document.getElementById('status');
  var closeBtn = document.getElementById('close');

alert('sdfsdfdsfdhgdhgfhfg');
  // Create a new WebSocket.
  var socket = new WebSocket('ws://192.168.1.105:8020'); //LAN Ip of host port 8020 is nginx reverse proxy 

  // Handle any errors that occur.
  socket.onerror = function(error) {
    socketStatus.innerHTML = 'WebSocket Error: ' + error;
  };

  // Show a connected message when the WebSocket is opened.
  socket.onopen = function(event) {
    socketStatus.innerHTML = 'Connected to: ' + event.currentTarget.url;
    socketStatus.className = 'open';
  };
  // Handle messages sent by the server.socketStat
  socket.onmessage = function(event) {
    var message = event.data;
    messagesList.innerHTML += '<li class="received"><span>Received:</span>' +
                               message + '</li>';
  };

  // Show a disconnected message when the WebSocket is closed.
  socket.onclose = function(event) {
    socketStatus.innerHTML = 'Disconnected from WebSocket.';
    socketStatus.className = 'closed';
  };
  // Send a message when the form is submitted.
  form.onsubmit = function(e) {
    e.preventDefault();
     socketStatus.innerHTML = 'PRESSED from WebSocket.';

    // Retrieve the message from the textarea.
    var message = messageField.value;
    // Send the message through the WebSocket.
    socket.send(message);

    // Add the message to the messages list.
    messagesList.innerHTML += '<li class="sent"><span>Sent:</span>' + message +
                              '</li>';

    // Clear out the message field.
    messageField.value = '';
    return false;
  };

  // Close the WebSocket connection when the close button is clicked.
  closeBtn.onclick = function(e) {
    e.preventDefault();
    // Close the WebSocket.
    socket.close();
    return false;
  };
};

Can somebody help me where am I going wrong?

All 3 comments

Did you add the proxy_set_header directive in your NGINX configuration?

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

worked like a charm!!! Thanks
Pains to just copy/paste a script from such answers without knowing what and how it works. Guess i have a lot to read on Nginx configurations.
Thanks again!!

Closing, feel free to continue discussing on the closed thread.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertmylne picture robertmylne  路  3Comments

makc picture makc  路  4Comments

ORESoftware picture ORESoftware  路  3Comments

dcflow picture dcflow  路  4Comments

bartosz-m picture bartosz-m  路  3Comments