c++socketsipwinsockets

Limiting the connections per ip with winsock


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?


Solution

  • 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;
    }