tags:

views:

57

answers:

2

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.

A: 

Well you can start with this tutorial, right out from my bookmarks. You can check the second argument of the function int listen(int sockfd, int backlog);.

sockfd is the usual socket file descriptor from the socket() system call. 
backlog is the number of connections allowed on the incoming queue. What 
does that mean? Well, incoming connections are going to wait in this queue 
until you accept() them (see below) and this is the limit on how many can 
queue up. Most systems silently limit this number to about 20; you can 
probably get away with settingit to 5 or 10

.

Praveen S
I setting backlog to 1 but it can connect.This is my result.server : new connection from ::1 on socket 4server : new connection from ::1 on socket 5
Atom Skaa ska Hic
@Praveen S: the listen backlog has nothing to do with number of active connections. Backlog only limits number of *pending* *un-accept()ed* connection attempts.
Dummy00001
+2  A: 

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

caf