首页 > 解决方案 > 与使用 AI_V4MAPPED 相关的 macOS getaddrinfo() 错误?

问题描述

当在 Linux (3.13.0) 和 macOS (10.15.7) 上运行时,我注意到简单程序showip.c( https://beej.us/guide/bgnet/examples/showip.c ) 的一个奇怪行为相同的程序给出了两个不同的结果(显然我不是指不同的 IPv4 地址):

Linux -> ./showip www.google.com
IP addresses for www.google.com:

  IPv4: 216.58.206.36
  IPv6: 2a00:1450:4002:800::2004
Linux -> 

在 macOS 上:

macOS -> ./showip www.google.com
IP addresses for www.google.com:

  IPv4: 142.250.180.100
macOS -> 

然而,当线

hints.ai_flags |= AI_V4MAPPED; 

在 macOS 版本的提示定义中添加,macOS 也会打印 IPv6 地址。这令人惊讶,而且,我不明白这是 AI_V4MAPPED 的语义。一个 macOS 错误?

代码:

/*
** showip.c -- show IP addresses for a host given on the command line
*/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
    struct addrinfo hints, *res, *p;
    int status;
    char ipstr[INET6_ADDRSTRLEN];

    if (argc != 2) {
        fprintf(stderr,"usage: showip hostname\n");
        return 1;
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
    hints.ai_socktype = SOCK_STREAM;

    if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
        return 2;
    }

    printf("IP addresses for %s:\n\n", argv[1]);

    for(p = res;p != NULL; p = p->ai_next) {
        void *addr;
        char *ipver;

        // get the pointer to the address itself,
        // different fields in IPv4 and IPv6:
        if (p->ai_family == AF_INET) { // IPv4
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
            addr = &(ipv4->sin_addr);
            ipver = "IPv4";
        } else { // IPv6
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
            addr = &(ipv6->sin6_addr);
            ipver = "IPv6";
        }

        // convert the IP to a string and print it:
        inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
        printf("  %s: %s\n", ipver, ipstr);
    }

    freeaddrinfo(res); // free the linked list

    return 0;
}

标签: linuxmacosipv6ipv4getaddrinfo

解决方案


推荐阅读