weeeez21
weeeez21

Reputation: 95

Bind error in IPv6 server

I'm trying make IPv6 server, but i have issue with socket binding. "could not bind socket"

All code:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdbool.h>

int main(int argc, char *argv[]) {

    int server_port = 8877;

    struct sockaddr_in6 server_address;
    memset(&server_address, 0, sizeof(server_address));

    server_address.sin6_family = AF_INET6;
    server_address.sin6_port = htons(server_port);
    server_address.sin6_addr = in6addr_any;


    int sockfd;

    if (sockfd = socket(AF_INET6, SOCK_STREAM, 0) < 0) {
        printf("could not create listen socket\n");
        return 1;
    }


    if (bind(sockfd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
        printf("could not bind socket\n");
        return 1;
    }

    int numberOfClients = 1;


    if (listen(sockfd, numberOfClients) < 0) {
        printf("could not open socket for listening\n");
        return 1;
    }


    struct sockaddr_in client_address;
    int client_len = 0;


    char buff4[INET_ADDRSTRLEN];

    while (1) {


        int sock;
        if ((sock =
                 accept(sock, (struct sockaddr *)&client_address,
                        0)) < 0) {
            printf("could not open a socket to accept data\n");
            return 1;
        }

        //printf("client connected with ip address: %s\n", inet_ntop(AF_INET, &(client_address.sin_addr), buff4, INET_ADDRSTRLEN));



        int n = 0;
        int len = 0, maxlen = 100;
        char buffer[maxlen];
        char *pbuffer = buffer;

        printf("client connected with ip address: %s\n",
               inet_ntoa(client_address.sin_addr));


        while ((n = recv(sock, pbuffer, maxlen, 0)) > 0) {
            pbuffer += n;
            maxlen -= n;
            len += n;

            printf("received: '%s'\n", buffer);

            // echo received content back
            send(sock, buffer, len, 0);
        }

        close(sock);
    }

    close(sockfd);
    return 0;
}

Upvotes: 0

Views: 558

Answers (1)

Michael Hampton
Michael Hampton

Reputation: 9980

The problem here is your order of operations.

You have written:

    if (sockfd = socket(AF_INET6, SOCK_STREAM, 0) < 0) {

You expected this to assign the return value of socket() to sockfd. But instead, it compares that return value to 0, and whether that value is less than 0 is what is actually stored in sockfd.

Before comparing, you should use an extra pair of parentheses to make explicit that you want to do the assignment and only then do the comparison:

    if ((sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {

Better yet, make the code more maintainable by making it more obvious what is going on, by assigning first and then comparing separately.

    sockfd = socket(AF_INET6, SOCK_STREAM, 0);
    if (sockfd < 0) {

Upvotes: 2

Related Questions