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
You (almost) always want to Accept
the connection, because the decision whether or not to connect can only come based on information sent from the client (user name, password, etc).
So after you establish a connection, run your authorization module to gather the authentication information and based on that, decide whether or not to call Close
on client
(in your example).
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 Listen
ing 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 Listen
ing socket after it accepts a connection, but this is generally a bad idea.