If I want to accept a connection I call accept
, but how can I refuse a connection?
In a working socket echo client I have this if statement. In the echo server, how can I make the echo client reach this printf
statement?
... if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) { printf("Connecting failed\n"); return 1; } ...
In short, 'failed to connect socket connection timed out error' can occur due to wrong SMTP host or port settings, ISP firewall blocks and more.
The Session and Subscription timeouts exists to give clients time to recover when communication is interrupted. So closing a socket without calling CloseSession means the timeouts need to be honoured because the Server cannot know if it was a network issue and the Client intends to reconnect or if it is gone forever.
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With