2013-11-27 161 views
0

瞭解TCP連接。任何人都可以看到爲什麼我的accept()調用與「無效參數」錯誤?我看不到我做錯了什麼。謝謝!accept()返回無效參數

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; 
} 

回答

6

listen的調用bindaccept前失蹤。

+0

確認!非常感謝! – Alex

-1

我將addr_size初始化爲sizeof(clientAddr)並清除clientAddr

+0

如果您在調用accept之前不初始化addr_size to sizeof(clinetAddr),內核將不知道作爲參數傳遞的地址引用包含所需的空間,以便從連接來的位置複製地址。我希望這解釋 - 從手冊頁接受 - addrlen參數是一個值結果 參數:它應該最初包含由addr指向的結構的大小 – CodeQ