Having trouble connecting client to server with IPv6 addresses (echoclient/echoserver pair)

50 views Asked by At

I'm programming an echoclient/server pair, with the goal of being IP agnostic/accepting IPv4 and IPv6. The intention is to send a message from my client to my server and have the server relay the message. I've followed Beej's guide pretty closely and deviated where necessary, but no matter what I do, I can't get it to work with an IPv6 address. Here is the relevant part of my client code:

    char buffer[16];
    int return_value;
    memset(&hints, 0, sizeof(hints)); // Initialize contents of hints to 0
    hints.ai_family = AF_UNSPEC; // Allow both IPv4 and IPv6
    hints.ai_socktype = SOCK_STREAM; // Stream socket for TCP

    if ((return_value = getaddrinfo(hostname, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(return_value));
        return 1;
        }

    // loop through all the results and connect to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
            p->ai_protocol)) == -1) {
            perror("client: socket");
            continue;
        }

        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("client: connect");
            continue;
        }

        break;
    }

I've tried changing ai_family to only IPv6, but that didn't make a difference. I'm getting an output of "client: connect: Cannot assign requested address client: failed to connect".

0

There are 0 answers