milanHrabos
milanHrabos

Reputation: 1965

bind: invalid argument when trying to bind AF_INET6 to INADDR_ANY (to localhost)

As far as I know, the IPv6 loopback is ::1. So when I try this:

//includes of all needed headers in one place
#include <include.h>

#define BACKLOG 10

int main(int argc, char const *argv[])
{
    if (argc != 2)
    {
        die("Usage: %s <port>\n", argv[0]);
    }
    int port = atoi(argv[1]);
    int numOfClient = 0;

    int sockfd = socket(AF_INET6, SOCK_STREAM, 0);
    struct sockaddr_in servaddr;

    servaddr.sin_family = AF_INET6;
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(port);

    if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        perror("bind");
    }
    else
    {
        printf("[+]bind\n");
    }
    if (listen(sockfd, BACKLOG) < 0)
    {
        perror("listen");
    }
    else
    {
        printf("[+]listening\n");
    }
    while (1)
    {
        int client_sockfd = accept(sockfd, NULL, NULL);
        time_t now = time(NULL);
        char *time_fmt = ctime(&now);
        numOfClient++;

        printf("client %d  requested for time at %s\n", numOfClient, time_fmt);
        if (write(client_sockfd, time_fmt, strlen(time_fmt) + 1) < 0)
        {
            die("died: write to client_sockfd\n");
        }
    }
    return 0;
}

and try to run this as :

$ # run with random port 4444
$ ./server6 4444
bind: Invalid argument
[+]listening

There was no problem for IF_INET socket, but with IF_INET6 it seems to have some sort of problem. What it could be?

Upvotes: 2

Views: 735

Answers (1)

dbush
dbush

Reputation: 225342

You're using the wrong sockaddr structure type. For IPv6 you need to use a struct sockaddr_in6.

struct sockaddr_in6 servaddr = { .sin6_family = AF_INET6, 
                                 .sin6_addr = IN6ADDR_ANY_INIT,
                                 .sin6_port = htons(port));

Or:

struct sockaddr_in6 servaddr = {0};

servaddr.sin6_family = AF_INET6;
servaddr.sin6_addr = in6addr_any;
servaddr.sin6_port = htons(port);

Upvotes: 5

Related Questions