0

How do you limit connections per IP with winsock?
Lets say I wanted to limit them to 20 connections per IP then don't accept the connection once its reach the limit.

I can't think of the logic on doing this.

I've thought of using callbacks on WSAAccept() and log into a database each ip before accepting a connection and list it on the db for each connection made.

[check if column count is <= 20]
return CF_ACCEPT;
}else{
return CF_REJECT;

But is there a more efficient way of doing this?

Priscilla Jobin
  • 609
  • 7
  • 19
zikdaljin
  • 95
  • 2
  • 5
  • 14

1 Answers1

0

I wouldn't use a database for this. A simple in-memory lookup table would suffice, such as a std::map. But in general, you are on the right track using a WSAAccept() callback. The only other option is to accept a connection and then immediately close it if needed.

Update: an example of using a std::map:

#include <map>

std::map<ulong, int> ipaddrs;
...

// when a client connects...
ulong ip = ...;
int &count = ipaddrs[ip];
if (count < 20)
{
    ++count;
    return CF_ACCEPT;
}
else
{
    return CF_REJECT;
}

...


// when an accepted client disconnects...
ulong ip = ...;
int &count = ipaddrs[ip];
if (count > 0)
{
    --count;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • How does `map` work here? Its the first time I've heard of this function. – zikdaljin May 16 '13 at 19:31
  • [`std::map`](http://en.cppreference.com/w/cpp/container/map) is not a function, it is a class that holds key/value pairs. You could use the IP address as a key and an `int` counter as the value. When a client is accepted, put its IP in the `std::map` if it does not already exist, and then increment its counter. When a client disconnects, decrement its IP counter, and remove it from the `std::map` if the counter falls to 0. – Remy Lebeau May 16 '13 at 20:27
  • Can I see a sample usage sir? – zikdaljin May 18 '13 at 07:21