Is there a way to limit the number of connections to a socket.io server from the same IP address? For example, I could set the limit to 3, and then when someone opened 4 tabs to join the server, three of them would connect and the fourth or any after wouldn’t get connected.
I’m not trying to cap the number of connections total, just for one person.
What’s the best way of doing this?
Edit: the servers are running on node.js, and the client is in js on a web browser
Advertisement
Answer
Of course, if the user had VPN, the IP address would be disabled. But still, there might be another way of doing this.
> One: Every time a user joins the page, give them an id, and store it in a variable server-side.
socket.on('connection', () => { users++ });
which will add the number of users connected.
> Two: Create a unique ID and cancel the “users++
” so the user doesn’t get counted again.
var users = 0; var userArray = []; var ip = /* Get the IP address here */; socket.on('connection', () => { if (users >= 3) { // The max users have arrived. (3 is the amount of users). // Do what you want to block them here. } // Check if the user's IP is equal to one in the array if (userArray.indexOf(ip) > -1) { // Cancel adding them to number of users return; } else { // Add IP to the array userArray.push(ip); users++; // Do what you want here. } });
If you’re using Node.js for your Socket server, I recommend getting the IP like this:
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim();