Blackbinary
Blackbinary

Reputation: 3986

Differentiating Between Sockets using Select

I'm making a TCP/IP server which listens on multiple ports. I chose to use select to enable handling of multiple events.

So, at the moment, I have two sockets, which are connected to two different ports (3000, 3001).

Once I'm inside the select loop, I want the server to respond differently based on the port that it is currently handling. How can I tell what socket I'm on, once inside the select?


I'm adding the code for my selection loop, hopefully you guys can point me in the right direction. Notice that this starts after I've added both file descriptors to the set.

while(1)

{

    /* Block until input arrives on one or more active sockets. */

    readfds = activefds;

    if (select (FD_SETSIZE, &readfds, NULL, NULL, NULL) < 0)

    {

        perror ("select");

        exit (EXIT_FAILURE);

    }

    

    /* Service all the sockets with input pending. */

    for (i = 0; i < FD_SETSIZE; ++i)

    {

        if (FD_ISSET (i, &readfds))

        {

            if (i == S_time)

            {

                
                if ((NS = accept(S_time,NULL,NULL)) < 0)

                    ERROR("server: accept");

                FD_SET(NS, &activefds); //add the new socket desc to our active connections set

                send_time(NS);

                

            }

            else if (i == S_remote)// i == S_remote

            {

                fprintf(stderr,"Remote");

                int status = recieve_request(S_remote);

                /* Data arriving on an already-connected socket. */

                

            }

            else

            {

                break;

            }

        }

    } /* //end of for */

} /* //end of while */

So my two sockets are S_time and S_remote. When a client connects to the time socket, I want to send that client the current time. When a client connects to remote, I was want to do remote execution. How can I make this distinction?

Upvotes: 1

Views: 973

Answers (2)

Check this explanation and sample code, seems that it answers your question. In brief, after select() returns, the corresponding descriptor is included in the corresponding set. For details follow the link.

Upvotes: -1

Brian Roach
Brian Roach

Reputation: 76898

select() deals with file descriptors, it doesn't know anything about the port number.

You would need to keep track of this information yourself (via a map keyed by the file descriptor, for example) or simply use multiple sets of file descriptors (where each set is specific to a port) and call select with a zero timeout (non-blocking) on each set.

Upvotes: 2

Related Questions