简体   繁体   中英

Socket.io - limit connections per IP address

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?

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).
}
// 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++;
});

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM