参数无效:connect()C套接字编程

时间:2013-09-08 16:51:20

标签: c sockets

我正在开发一个在客户端和服务器之间建立连接的C程序。当我在已经创建的套接字上运行connect时,我一直收到一个错误,我正在传递一个无效的参数。

任何帮助都会很棒!

void client(char* ipAddress, char* serverPort){
    //code for setting up the IP address and socket information from Beej's Guide to Network Programming
    //Need to setup two addrinfo structs. One for the client and one for the server that the connection will be going to
    int status;
    //client addrinfo
    struct addrinfo hints, *res; // will point to the results
    //server addrinfo
    int socketDescriptor;
    int addressLength;
    memset(&hints, 0, sizeof hints); // make sure the struct is empty
    hints.ai_family = AF_UNSPEC;     // don't care IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
    hints.ai_flags = AI_PASSIVE;     // fill in my IP for me
    //setup client socket
    if ((status = getaddrinfo(ipAddress, serverPort, &hints, &res)) != 0) {
      printf("%s \n", "This error above");
      fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
      exit(1);
    }

    if((socketDescriptor = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) ==-1){
      perror("client: socket");
    }
    addressLength = sizeof hints;
    if(connect(socketDescriptor, res->ai_addr, addressLength)==-1){
      close(socketDescriptor);
      perror("client: connect");
    }
  }

1 个答案:

答案 0 :(得分:1)

除了代码中的一些不一致的变量名称, 这似乎是错的:

addressLength = sizeof hints;
if(connect(socketDescriptor, res->ai_addr, addressLength)==-1) ...

应该是

if(connect(socketDescriptor, res->ai_addr, res->ai_addrlen)==-1) ...