csockets

How can I refuse a socket connection in C?


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; 
}
...

Solution

  • 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.