How can I refuse a socket connection in C?
To get the behavior you want (only accept one connection at a time, other clients attempting should get a failure), there are two choices.
You can close your listen socket after you have accepted a connection. Re-create your listen socket after the accepted connection closes.
You can close newly established connections if there is already a connection in progress. If you want the client to see a TCP reset, most TCP stacks will trigger one if you enable the linger option with a timeout of 0.
struct linger lo = { 1, 0 };
setsockopt(s, SOL_SOCKET, SO_LINGER, &lo, sizeof(lo));
close(s);
To my knowledge, that isn't how TCP works. The accept(..)
call will always return with the client details. There is no way to peek at the connection and selectively refuse.
The way you are doing it now is actually the correct way: accept and then close. In case you have another message structure over and above this layer, you can create a custom "Reject message". This option completely depends on your use case.
In case you are looking for rejecting on the basis of IP address, its not within your apps domain. Its the job of your firewall (As @Bart Friederichs says). That way, the request will not even touch the TCP stack.
Actually I want strictly one connection only on this particular port. Any other connection should ideally fail in a very obvious way.
Do not let the accept call in your control flow. Only when you wait on accept
will your program wait for a socket connection, never otherwise.
In standard socket APIs on most platforms, there is no way to reject a connection. You must accept()
the connection and then close it immediately if you don't want it.
The exception to this rule is the Winsock-specific WSAAccept()
function. It provides a callback that allows an application to decide, on a per-connection basis, whether a connection should be accepted, rejected, or kept in the backlog queue.