AndroidDev
AndroidDev

Reputation: 21237

accept() returning invalid argument

Learning about TCP connections. Can anyone see why my accept() call is erroring with an "invalid argument"? I can't see what I am doing wrong. Thanks!

int main(int argc, char *argv[]) {

    int sockfd, newfd;

    struct sockaddr_in clientAddr;
    unsigned int recvLen;
    socklen_t addr_size;

    fd_set read_set;
    struct timeval tv;

    // initialize the fd set
    FD_ZERO(&read_set);

    // prepare the address struct for the first client
    bzero(&clientAddr,sizeof(clientAddr));                          //zero the struct
    clientAddr.sin_family = AF_INET;                              //address family (ipv4)
    clientAddr.sin_port = htons(6001);  //sets port to network byte order
    clientAddr.sin_addr.s_addr = INADDR_ANY;
    addr_size = sizeof(clientAddr);

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        fprintf(stdout, "Cannot create socket for client 0.\n");
        fprintf(stdout, "Terminating program\n\n");
        exit(1);
    } else {
        fprintf(stdout, "Socket established for client 0\n");
    }

    if (bind(sockfd, (struct sockaddr *)&clientAddr, sizeof(clientAddr)) < 0) {
        fprintf (stdout, "Binding failed for client 0\n\n");
        perror("bind failed");
        exit (1);
    } else {
        fprintf (stdout, "Binding successful for client 0\n");
    }

    // ERROR HAPPENS ON THE NEXT LINE
    if ((newfd = accept(sockfd, (struct sockaddr *)&clientAddr, &addr_size)) < 0) {
    fprintf(stdout, "Error accepting inbound data from client 0\n");
        perror(" accept() failed");
        exit(EXIT_FAILURE);
    } else {
        fprintf(stdout, "\tSuccessfully accepted inbound connection from client 0\n");
    }

    return 0;
}

Upvotes: 0

Views: 3108

Answers (2)

CodeQ
CodeQ

Reputation: 319

I would initialize addr_size to sizeof(clientAddr) and clear clientAddr

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136495

A call to listen is missing after bind before accept.

Upvotes: 8

Related Questions