With some research I found a method to do this by looking at the Public IP address. I found a useful free API: http://ipify.org, but I wanted to keep it server side. This question answered how to get the IP from a request, but I decided to use request-ip
.
Any thoughts on this approach? Obviously there is a very low chance of two networks having the same IPv4 address.
Here is a working example and below is the code.
index.js
const path = require('path');
const express = require("express");
const socket = require('socket.io');
const requestIp = require('request-ip');
const app = express();
const server = app.listen(8080, () => console.log(`listening on port ${server.address().port}`));
const io = socket(server);
let networks = {};
app.get('/', (req, res) => {
res.sendFile( path.join( __dirname, 'index.html') );
});
io.on('connection', function (socket) {
let clientIP = requestIp.getClientIp(socket.request);
console.log('New connection from ' + clientIP);
if( networks[clientIP] == undefined ){ networks[clientIP] = []; };
let network = networks[clientIP];
network.push(socket);
updateNetwork(network);
socket.on('disconnect', function () {
console.log('Disconnected ' + clientIP);
network.splice(network.indexOf(socket), 1);
updateNetwork(network);
});
});
function updateNetwork(network){
for( let socket of network ){
socket.emit( 'network-clients', network.length );
}
}
index.html
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<p>
Clients Connected on the same network: <span id="network-clients">loading...</span>
</p>
</body>
<script>
let socket = io.connect(window.location.origin);
socket.on('network-clients', (data) => {
document.getElementById('network-clients').innerHTML = data;
});
</script>
</html>