Search code examples
c#socketstcp

How to reject a connection attempt in c#?


I have a socket that listens for connections. What I want to do is to have an accept / reject option when a connection is attempted. This is my code:

private void StartListening()
{
    while (running)
    {
        AcceptingSocket.Listen(100);
        Socket client = AcceptingSocket.Accept();

        if (IncomingConnection!= null)
        {
            TcpEventArgs eventArgs = new TcpEventArgs(client);
            IncomingConnection(eventArgs);
        }
    }
}

Is there a way that the .Accept checks if the user wants to accept or reject the connection?


Solution

  • As @Blindy has said, you need to accept the incoming connection, then close it if you decide that you don't want to proceed with that connection. Until Accept returns, you don't have a reference to the Socket, so are unable to do anything that would allow you to make a decision about whether or not to accept, based on the client (such as check supplied credentials, or the source address for the connection).

    From the client's perspective, once they have connected to the Listening socket, the connection is established (the connection is established to the listening port by the OS, then handed over to you in the Accept call). You cannot fake a 'Connection Refused / The other side actively refused the connection' type error on a Socket that is in a listening state. So Accept, followed by Close, would look the same to the client as if there was some way for Accept to abort the connection.

    If you've got a programmatic reason for not allowing more connections (such as you only want one client at a time), then you could shutdown the Listening socket after it accepts a connection, but this is generally a bad idea.