Get IPv4 Address of client in socket.io - node.js

When I log the 'socket' object during socket.on('connection'), I get the following information:
_peername: { address: '::1', family: 'IPv6', port: 57535 }
How do I change the family to IPv4 during socket connection?

I was testing around and found that on the client if I use
var socket = io('http://localhost:8000', { transports: ['websocket']});
the socket.handshake.address returns ::1
If I use
var socket = io('http://server_ip:8000', { transports: ['websocket']});
the socket.handshake.address return ::ffff:ipv4address

When you create an http instance, make sure you bind your connection to an IPv4 address.
Example:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
http.listen(8000, '0.0.0.0', function(){
console.log('listening on *:8000');
});
That should do the trick. :)

This should listen on IPv4; Try it and let me know...
var net = require('net');
var server = net.createServer();
server.on('connection', handleConnection);
server.listen({
host: 'localhost',
port: 8000,
exclusive: true
}, function() {
console.log('server listening to %j', server.address());
});
Output:
server listening to {"address":"127.0.0.1","family":"IPv4","port":8000}

Related

How to troubleshoot problem with setting WebRTC server on vps?

I wrote a simple node express server for webRTC using peerjs-server and simple client using peerjs. Everything works fine on localhost, but when I try it on vps, I get error:
Firefox can't connect with server ws://my.vps/peerjs/peerjs?key=peerjs&id=hj3hpekwaa38fr00&token=ymtfvhagiw
PeerJS: Socket closed.
PeerJS: ERROR Error: Lost connection to server.
Error: "Lost connection to server."
emitError https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:16426
_initializeServerConnection https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:12260
emit https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:25516
onclose https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:19350
Server:
const express = require('express');
enter code here`const app = express();
const ExpressPeerServer = require('peer').ExpressPeerServer;
app.use(express.static('./public'));
const server = app.listen(80, () => { // 3000 on localhost
console.log('Express server listen on port ' + 80);
});
const options = { debug: true };
const peerserver = ExpressPeerServer(server, options);
app.use('/peerjs', peerserver);
app.use('/*', express.static('./public/index.html'));
Client:
var peer = new Peer('', {
host: location.hostname,
port: location.port || (location.protocol === 'https:' ? 443 : 80),
path: '/peerjs',
debug: 3
});
peer.on('open', function (id) {
console.log(id);
});
Any help appreciate.
It looks like you are connecting with server ws://my.vps/, which is a web socket to a server at http://my.vps/ which doesn't seem to exist.
It should probably also be using https (or wss)

Cant connect to WebSocket Node.JS

i'm making a game that use WebSockets and this is the code that i use to start a WebSocket server:
const server = require("http").Server(app);
const port = 3005;
server.listen(port, () => {
console.log('Server started on port: ' + port);
});
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server })
wss.on('connection', function connection(ws) {});
And this code i use for connecting a user to the WebSocket:
this.SERVER_URL ='ws://localhost/?fvukovic'; <-- fvukovic is the user
this.ws = new WebSocket(this.SERVER_URL, ["test"]);
this.ws.onopen = () => {
console.log('open');
};
This works perfectly, but when i push that on server and i change the ip address to 195.201.119.221 which is the ip of the server, port is still 3005, i cant connect to it anymore..
I get this error:
WebSocket connection to 'ws://195.201.119.221:3005/?fvukovic' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
Do i need something more when i put the the app on a real server?

Https server with socket and express

I'm using SSL to encrypt my backend but my current solution opens two ports, one for sockets and the other for express, any approach to start both on the same port like HTTP ?
const port=4000;
if(process.env.ENABLE_SSL=='true')
{
////two ports are open 8989,4000
server = https.createServer({
key: fs.readFileSync("sslLocation/ssl.key"),
cert: fs.readFileSync("sslLocation/ssl.cert")
},app).listen("8989", '0.0.0.0',function(){
console.log('Express server listening to port 8989');
});
global.io = require('socket.io').listen(server);
app.listen(port);
}
else
{
////one port only
// start the server
server = app.listen(port, function () {
console.log(`App is running at: localhost:${server.address().port}`);
});
global.io = require('socket.io').listen(server);
}
also running app.listen(server) in the ssl section, i can't access the apis

Exressjs: how to get https server address and port?

How can I get https server address and port with expressjs?
With http:
var server = app.listen(3000, "127.0.0.1", function () {
var host = server.address().address;
var port = server.address().port;
console.log(server.address());
console.log('Example app listening at http://%s:%s', host, port);
});
result:
{ address: '127.0.0.1', family: 'IPv4', port: 3000 } Example app
listening at http://127.0.0.1:3000
But with https:
https.createServer(options, app).listen(3000, "127.0.0.1", function () {
console.log('Started!');
var host = https.address;
var port = https.port;
console.log('Example app listening at http://%s:%s', host, port);
});
result:
Example app listening at http://undefined:undefined
Any ideas?
may be this link is helpful to you
https://docs.nodejitsu.com/articles/HTTP/servers/how-to-create-a-HTTPS-server/

node.js: proxy websockets to other port

I have written http proxy in node.js running on port 80. All I need is to redirect socket.io traffic to port 9090 and standard http traffic to Apache on 8080. This is my proxy code:
httpProxy = require('http-proxy');
httpProxy.createServer(function (req, res, proxy) {
if (req.url.match(/socket.io/)) {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9090
});
} else {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 8080
});
}
}).listen(80);
Everything works, but io.socket falls back to xhr-polling.
http://localhost/client.htm - falls back to xhr-polling
file:///C:/.../client9090.htm - still uses websocket
socket.io app is running on port 9090, client.htm connects to 80 and client9090.htm connects directly to 9090.
It looks like a node-http-proxy makes socket.io app to work in xhr-polling mode.
Client is Chrome v.25
socket.io app code
var io = require('socket.io').listen(9090);
io.on('connection', function (socket) {
socket.on('hi!', function (data) {
console.log(data);
socket.emit('news');
});
socket.on('ahoj', function (data) {
console.log(data);
});
});
client.htm code
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var chat = io.connect('http://localhost')
chat.on('connect', function () {
chat.emit('hi!');
});
chat.on('news', function () {
chat.emit('ahoj',{a:1,b:2});
});
</script>
client9090.htm is the same but localhost is replaced by localhost:9090
As I said, everythig works well, only problem is, that node-http-proxy makes to fall back from websockets to xhr-polling.
Can anyone help?
According to https://npmjs.org/package/http-proxy, when adding a callback to the httpProxy.createServer(), you have to manually proxy 'upgrade' events, so something like this:
httpProxy = require('http-proxy');
// added `var server =` here
var server = httpProxy.createServer(function (req, res, proxy) {
if (req.url.match(/socket.io/)) {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9090
});
} else {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 8080
});
}
}).listen(80);
// added upgrade listener section here:
server.on('upgrade', function (req, socket, head) {
server.proxy.proxyWebSocketRequest(req, socket, head);
});
However, for the usage you described above, you don't even need the callback function - you could just as easily do something like this:
httpProxy = require('http-proxy');
var options = {
pathnameOnly: true,
router: {
'/wiki': '127.0.0.1:8001',
'/blog': '127.0.0.1:8002',
'/api': '127.0.0.1:8003'
}
}
var proxyServer = httpProxy.createServer(options);
proxyServer.listen(80);

Resources