[IPv6] getaddrinfo()获取本机IPv4和IPv6地址

前言

getaddrinfo()可以方便的获取IPv6和IPv4地址。
记录一下,如何用getaddrinfo()获取本机的IPv6和IPv4地址。

参考

getaddrinfo 函数 (ws2tcpip.h)
getaddrinfo()函数详解

代码

↓获取本机hostname
环境:Virtual Studio 2022

#include 
#include 
#include 
#pragma comment(lib, "ws2_32.lib")

int main()
{
    WSADATA lpWSAData;
    WSAStartup(MAKEWORD(2,2), &lpWSAData);

    //get local host name
    char errmsg[256] = { 0x00 };
    struct in_addr addr;

    char local_host_name[256] = { 0x00 };
    if (gethostname(local_host_name, 256))
    {
        std::cout << strerror_s(errmsg,256,WSAGetLastError()) << std::endl;
        return -1;
    }
    std::cout << "local_host_name:" << local_host_name << std::endl;
    std::cout << std::endl;

↓通过getaddrinfo获取hostname对应的IP地址
hints.ai_family = AF_UNSPEC;是既接受IPv6也接受IPv4。
在获取getaddrinfo返回的地址时,一定要注意区分sockaddr_insockaddr_in6

#if 1 //IPv6 & Ipv4
    struct addrinfo hints, *res = NULL, *p = NULL;
    memset(&hints, 0, sizeof(hints));
    //hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    int e = getaddrinfo(local_host_name, NULL, &hints, &res);
    if (e != 0)
    {
        std::cout << "getaddrinfo error:" << gai_strerror(e) << std::endl;
        exit(2);
    }

    p = res;
    char bufff[512] = { 0x00 };
    while (p != NULL)
    {
        if (p->ai_family == AF_INET)
        {
            std::cout << "p->ai_family == AF_INET" << std::endl;;
            memset(bufff, 0x00, sizeof(bufff));
            inet_ntop(AF_INET, &((sockaddr_in*)p->ai_addr)->sin_addr, bufff, sizeof(bufff));
            std::cout << bufff << std::endl;
            std::cout << std::endl;
            
        }
        else if (p->ai_family == AF_INET6)
        {
            std::cout << "p->ai_family == AF_INET6" << std::endl;;
            memset(bufff, 0x00, sizeof(bufff));
            inet_ntop(AF_INET6, &((sockaddr_in6*)p->ai_addr)->sin6_addr, bufff, sizeof(bufff));
            std::cout << bufff << std::endl;
            std::cout << std::endl;
        }
        else
        {
            std::cout << "UNKNOWN" << std::endl;
            std::cout << std::endl;
        }
        p = p->ai_next;
    }
    freeaddrinfo(res);

#endif
    getchar();
    WSACleanup();
}

后记

没发现网上有getaddrinfo()获取IPv6地址的代码,虽然可能比较简单,但是还是记录一下,以免后面自己忘了。

你可能感兴趣的:(网络编程,网络,tcp/ip,windows)