Get IP address using uWebSockets - websocket

Please, how can I get sender IP address using uWebSockets?
const wss = new uws.Server({
server: server,
perMessageDeflate: false
});
wss.on(`connection`, ws => {
ws.remoteAddress = ws.upgradeReq.connection.remoteAddress;
console.log(`user connected: `, ws.remoteAddress);
});
user connected is undefined

Please try this:
wss.on(`connection`, ws => {
ws.remoteAddress = ws._socket.remoteAddress;
console.log(`user connected: `, ws.remoteAddress);
});
You can also log ws._socket to know what it is.

ws._socket.remoteAddress should work , but if you ws server is behind a load balancer, you can get it via :
ws.upgradeReq.headers["x-forwarded-for"]

Related

How to obtain client MAC, ip and other information in the 'ws.on('connection')' callback function?

This is the ws module, what I want to ask is how to get the client's MAC, ip and other information when connecting
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({
//...
}, () => {
});
wss.on('connection', function (ws, req) {}); //How to get client MAC, ip and other information?
I don't know what you mean by "other information", but req is an http.IncomingMessage, so the documentation would be a good starting point.
For example, the IP address is accessible as req.socket.localAddress.
You won't be able to get the MAC address.

Socket IO forbidden 403

I have a simple socket.io app and it works just fine on local and also it's installed successfully on AWS server using plesk admin dashboard but when I connect to the app I always get forbidden {"code":4,"message":"Forbidden"} .. the entry point seems to work great http://messages.entermeme.com .. any idea what could be wrong with it ?
Frontend code
import io from 'socket.io-client'
const socket = io('https://messages.entermeme.com', {
transports: ['polling'],
})
socket.emit('SUBSCRIBE')
Backend code
const cors = require('cors')
const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
server.listen(9000)
app.use(cors())
io.set('transports', [
'polling'
])
io.origins([
'http://localhost:8000',
'https://entermeme.com',
])
io.on('connection', (socket) => {
socket.on('SUBSCRIBE', () => {
//
})
})
had a similar issue but when using nginx. So in case you still need some help:
In the end it turned out to be the URL I specified as socket origins. I didn't specify the port since the origin for me was also running on port 80 (443 for SSL) like in your example above:
io.origins([
'http://localhost:8000',
'https://entermeme.com', // <--- No port specified
])
I updated my config and added the port. So for you it would be:
io.origins([
'http://localhost:8000',
'https://entermeme.com:80', // <--- With port (or 443 for SSL)
])

Cannot hit simple node web server hosted on EC2 instance

Not able to hit my simple node web server hosted on an ubuntu EC2 in AWS. But I can't see I've missed anything! I've provided screen shots below within AWS - What am I missing? Please help!.
Many thanks,
Node code
const http = require('http');
const hostname = '127.0.0.1';
const port = 8080;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Command prompt
$ node index.js
Command prompt response
Server running at http://127.0.0.1:8080/
EC2 instance
Security settings
Elastic IP settings
Browser
http://"Public DNS (IPv4) value":8080/
Update
When you select the type, select "Custom TCP Rule":
and enter 8080 in the port range field.
EDIT
However, that only gets you part of the way. If you notice, your server is listening on the IP address 127.0.0.1. That means that it's not listen to the outside world, only localhost. To access it outside of the server machine you'll need to change your code to:
const http = require('http');
const hostname = '0.0.0.0';
const port = 8080;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
The change is that you're now listening on "all interfaces" as compared to just localhost.

i am unclear of how to use socket.io-emitter (server to server)

Below is how i initialize and emit but i dont find any errors nor do my server listening, receives any events.
const io = require('socket.io-emitter')({
host: 127.0.0.1,
// path: do i need this ?
port: redisUri.port,
pub: pub, // is the key required to be the same as the app ?
sub: sub, // is the key required to be the same as the app ?
});
io.emit('test', 'test'})
i tried many variations, can someone enlighten me how can i debug this ?
ive tried to add a redis href before the object as well.
I found the error, the issue was with the pub and sub sockets.
Here's the solution:
var pub = redisPassword ? redis.createClient(6379, localhost, {return_buffers: true, auth_pass: redisPassword}) : undefined;
var sub = redisPassword ? redis.createClient(6379, localhost, {detect_buffers: true, return_buffers: true, auth_pass: redisPassword}) : undefined;
socketio.adapter(require('socket.io-redis')({ host: localhost, port: 6379, pubClient: pub, subClient: sub }));
This was the issue:
Instead of having it at undefined for the checking of password, I
created another client, it was easier to set it to default.
Please do let me know if I could improve my code. Thank you.

Socket.io connection url?

I have the current setup:
Nodejs Proxy (running http-reverse-proxy) running on port 80.
Rails server running on port 3000
Nodejs web server running on port 8888
So any request starting with /nodejs/ will be redirected to nodejs web server on 8888.
Anything else will be redirected to the rails server on port 3000.
Currently Socket.io requires a connection url for io.connect.
Note that /nodejs/socket.io/socket.io.js is valid and returns the required socket.io client js library.
However, I am not able to specify connection_url to /nodejs/ on my server.
I have tried http://myapp.com/nodejs and other variants but I am still getting a 404 error with the following url http://myapp/socket.io/1/?t=1331851089106
Is it possible to tell io.connect to prefix each connection url with /nodejs/ ?
As of Socket.io version 1, resource has been replaced by path. Use :
var socket = io('http://localhost', {path: '/nodejs/socket.io'});
See: http://blog.seafuj.com/migrating-to-socketio-1-0
you can specify resource like this:
var socket = io.connect('http://localhost', {resource: 'nodejs'});
by default resource = "socket.io"
If you are using express with nodejs:
Server side:
var io = require('socket.io')(server, {path: '/octagon/socket.io'});
then
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
socket.on('publish message ' + clientId, function(msg) {
console.log('got message')
})
Client side:
var socket = io('https://dev.octagon.com:8443', {path: '/octagon/socket.io'})
then
socket.emit('publish message ' + clientId, msg)
I use below approach to achieve this goal:
client side:
var socket = io.connect('http://localhost:8183/?clientId='+clientId,{"force new connection":true});
server side:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
console.log("url"+socket.handshake.url);
clientId=socket.handshake.query.clientId;
console.log("connected clientId:"+clientId);
});
reference:https://github.com/LearnBoost/socket.io/wiki/Authorizing#global-authorization
If you are serving your app with express, then maybe you can check this out. Remember express uses http to serve your application.
const express = require('express'),
http = require('http'),
socketIo = require('socket.io'),
app = express()
var server = http.createServer(app);
var io = socketIo(server);
io.on('connection', (socket)=>{
// run your code here
})
server.listen(process.env.PORT, ()=> {
console.log('chat-app inintated succesfully')
})

Resources