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



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

任何帮助都会很棒!

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: %sn", 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");
    }
  }

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

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

它应该是

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

最新更新