如何在Linux套接字编程中限制连接?

Ato*_*Hic 4 c sockets linux

我想设置连接的最大值.如果它超过最大值,请告诉客户端现在服务器已满并关闭套接字.

如何用C编写代码?

谢谢.

caf*_*caf 10

简单.在你打电话的地方accept(),这样的事情:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

(当然total_connections,在你失去联系的地方减少).