accept()返回无效参数

时间:2013-11-27 16:47:26

标签: c sockets tcp network-programming

了解TCP连接。任何人都可以看到为什么我的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;
}

2 个答案:

答案 0 :(得分:7)

listen bind之前accept之后,{{1}}的电话号码丢失了。

答案 1 :(得分:-1)

我会将addr_size初始化为sizeof(clientAddr)并清除clientAddr