Search code examples
cnetwork-programmingvxworks

how to restrict number of connections in client server program


I want a server program which should accept only maximum of one connection and it should discard other connections. How can I achieve this?


Solution

  • Only accept() a single connection.

    Here is a typical server routine:

    s = socket(...);
    bind(s, ...);
    listen(s, backlog);
    while (-1 != (t = accept(s, ...))) {
        // t is a new peer, maybe you push it into an array
        // or pass it off to some other part of the program
    }
    

    Every completed accept() call, returns the file descriptor for a new connection. If you only wish to receive a single connection, only accept() once. Presumably you're done listening after this, so close your server too:

    s = socket(...);
    bind(s, ...);
    listen(s, backlog);
    t = accept(s, ...);
    close(s);
    // do stuff with t
    

    If you wish to only handle a single connection at a time, and after that connection closes, resume listening, then perform the accept() loop above, and do accept further connections until t has closed.