绑定:尝试将 AF_INET6 绑定到 INADDR_ANY(到本地主机)时参数无效

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

据我所知,IPv6环回是::1。所以当我尝试这个时:

//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;
}

并尝试将其 运行 设为 :

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

IF_INET 套接字没有问题,但 IF_INET6 似乎有一些问题。它可能是什么?

您使用了错误的 sockaddr 结构类型。对于 IPv6,您需要使用 struct sockaddr_in6.

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

或者:

struct sockaddr_in6 servaddr = {0};

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