尝试从C

时间:2017-05-18 21:33:19

标签: c sockets

我有以下代码:

void startMQTTPassthroughServer() {
  struct addrinfo hints, *res;  // res will point to the result given by getaddrinfo()
    struct sockaddr_storage their_addr;
    socklen_t addr_size;
    int sock, cli;  // server and client socket descriptors
    int status;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;    // IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM;    // TCP socket
    hints.ai_flags = AI_PASSIVE;    // Fill my IP for me

    if((status = getaddrinfo(NULL, LISTEN_PORT, &hints, &res)) != 0) {
        fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
        exit(1);
    }

    if((sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) {
        perror("socket: ");
        exit(-1);
    }

    printf("Creating Socket.......OK\n");

    if((bind(sock, res->ai_addr, res->ai_addrlen)) == -1) {
        perror("bind: ");
        exit(-1);
    }

    freeaddrinfo(res);  // Free the res pointer

    if((listen(sock, 8)) == -1) {
        perror("listen: ");
        exit(-1);
    }

    printf("Listening on port 1883.......OK\n");


    while(1) {
        if((cli = accept(sock, (struct sockaddr *)&their_addr, &addr_size)) == -1) {
            perror("accept: ");
            exit(-1);
        }
        printf("Client connected: Identifier - %d\n", cli);

    readDataFromClient(cli);
    }
}

当我尝试将客户端连接到此服务器时,我收到错误消息"无效的参数"当调用accept函数时。我是否将正确的参数传递给接受电话?如果没有,那么正确的论点是什么?

0 个答案:

没有答案