Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit connection in Linux socket programming?

Tags:

c

linux

sockets

I want to set the maximum of connection. If it more than the maximum, tell the client now server is full and close the socket.

How to write code in C ?

Thank you.

like image 578
korrawit Avatar asked Aug 30 '10 04:08

korrawit


1 Answers

Simple. At the point where you call accept(), something like this:

new_conn = accept(listen_sock, &addr, addr_len);

if (new_conn > 0)
{
    if (total_connections < max_connections)
    {
        total_connections++;
        register_connection(new_conn);
    }
    else
    {
        send_reject_msg(new_conn);
        close(new_conn);
    }
}

(and of course decrement total_connections at the point where you lose a connection).

like image 150
caf Avatar answered Sep 28 '22 06:09

caf