Jaideepb
Jaideepb

Reputation: 11

select listen socket always succeeds

I am doing a toy server-client project(on linux) where multiple clients connect to server and do remote execution on server. What I have is a select() call which is supposed to tell me when a socket is readable. This is for both listen and accept new connection. Below I am posting a snippet.

int main() {
    int sockfd;
    fd_set readfds;
    struct sockaddr_in serv_addr,cli_addr;
    struct timeval tv;
    socklen_t clilen = sizeof(cli_addr); 

    sockfd=socket(AF_INET, SOCK_STREAM, 0);
    //setsockopt(sockid,IPPROTO_IPV6,IPV6_V6ONLY,(char *)&yes,sizeof(yes));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr =inet_addr("127.0.0.1");// INADDR_ANY;
    serv_addr.sin_port = htons(40000);

    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
    {
        perror("bind");
    }

    while(1)
    {
        FD_ZERO(&readfds);
        FD_SET(sockfd,&readfds);

        tv.tv_sec=2;
        tv.tv_usec=500000;

        int result =select(sockfd+1,&readfds,NULL,NULL,&tv);
        if(result<0) {
            exit(-1);
        }
        else if(result>0) {
            if(FD_ISSET(sockfd,&readfds)) {
                //int newsockfd =accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
                int newsockfd =accept(sockfd,NULL,NULL);
                if(newsockfd<0) {
                    perror("accept");
                }
            }
        }
    }


    return 0;
}

But the select in the above code is always succeeding irrespective of the presence of any client and the accept is throwing error: "accept: Invalid argument" and keep on looping, select is not even waiting for the timeout. Can someone please explain what is problem with my code. Am I not using select the right way it is supposed to be used(I am using it for the first time)?

Upvotes: 1

Views: 431

Answers (1)

pat
pat

Reputation: 12749

You forgot to call listen after bind.

Upvotes: 3

Related Questions