Boost :: asio async_accept Deny Connection

My application has an asio socket server which should accept connections from a specific list of IP addresses.

This filter should be executed by the application (and not the system), since it can change at any time (I should be able to update this list at any time)

The client should receive an acces_denied error.

I assume that when the handle_accept callback is called, the SYN / ACK is already sent, so you don’t want to accept, then close brutally when I find that the associated ip address is not resolved. I don’t control the client’s behavior, maybe it doesn’t act the same way when the connection is refused and just closed by the peer, so I want to make everything clean. (but this is what impresses at the moment)

Do you know how I can do this?

My access list is a container std :: strings (but I can convert it to a counter for something else ...)

Many thanks

+5
source share
2 answers

The async_accept method has an overload to get the endpoint of the peer. You can compare this value inside your handler async_accept. If it does not match the entry in your container, allow the socket to go out of scope. Otherwise, process it as required by your application.

+4
source

I do not know the details of your application, but that is exactly how I would do it.

In the accept / lambda handler

void onAccept(shared_ptr<connection> c, error_code ec)
{
    if (ec) { /*... */ }
    if (isOnBlackList(c->endpoint_))
    {
       c->socket_.async_write( /* a refusal message */, 
         [c](error_code, n) 
         { 
            c->socket_.shutdown();
            // c fizzles out of all contexts... 
         });
    }
    else
    {
        // successful connection execution path
    }
}
0

All Articles