简体   繁体   中英

Invalid Argument: connect() C socket programming

I'm working on a C program that creates a connection between a client and server. When I run connect on the socket I've already created I keep getting an error that I'm passing an invalid argument.

Any help would be awesome!

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

Apart from some inconsistent variable names in your code, this seems to be wrong:

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

It should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM