简体   繁体   English

从 URL 获取 IP (C++)

[英]Get IP from URL (C++)

How can I get the IP-address from a domain name with the top level domain name?如何从具有顶级域名的域名中获取 IP 地址? In this example get the IP of google.com.在本例中获取 google.com 的 IP。 And if possible in IPv6 in the correct format.如果可能的话,在 IPv6 中以正确的格式。

This is what I've tried so far:这是我迄今为止尝试过的:

#include <netdb.h>

using namespace std;

int main()
{
    struct hostent* myHostent;
    myHostent = gethostbyname("google.com");
    cout<<myHostent <<"\n";
    //output is a hex code
    cout<<myHostent->h_name<<"\n";
    //output is google.com
    cout<<myHostent->h_aliases;
    //output is a hex code  
}

The domain's IP addresses (yes plural, there can be more than 1) is in the hostent::h_addr_list field, not in the hostent::h_aliases field, eg:域的 IP 地址(是复数,可以超过 1 个)在hostent::h_addr_list字段中,而不在hostent::h_aliases字段中,例如:

int main()
{
    hostent* myHostent = gethostbyname("google.com");
    if (!myHostent)
    {
        cerr << "gethostbyname() failed" << "\n";
    }
    else
    {
        cout << myHostent->h_name << "\n";

        char ip[INET6_ADDRSTRLEN];
        for (unsigned int i = 0; myHostent->h_addr_list[i] != NULL; ++i)
        {
            cout << inet_ntop(myHostent->h_addrtype, myHostent->h_addr_list[i], ip, sizeof(ip)) << "\n";
        }
    }

    return 0;
}

That said, gethostbyname() is deprecated, use getaddrinfo() instead, eg:也就是说,不推荐使用gethostbyname() ,请改用getaddrinfo() ,例如:

void* getSinAddr(addrinfo *addr)
{
    switch (addr->ai_family)
    {
        case AF_INET:
            return &(reinterpret_cast<sockaddr_in*>(addr->ai_addr)->sin_addr);

        case AF_INET6:
            return &(reinterpret_cast<sockaddr_in6*>(addr->ai_addr)->sin6_addr);
    }

    return NULL;
}

int main()
{
    addrinfo hints = {};
    hints.ai_flags = AI_CANONNAME;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    addrinfo *res;

    int ret = getaddrinfo("google.com", NULL, &hints, &res);
    if (ret != 0)
    {
        cerr << "getaddrinfo() failed: " << gai_strerror(ret) << "\n";
    }
    else
    {
        cout << res->ai_canonname << "\n";

        char ip[INET6_ADDRSTRLEN];
        for(addrinfo addr = res; addr; addr = addr->ai_next)
        {
            cout << inet_ntop(addr->ai_family, getSinAddr(addr), ip, sizeof(ip)) << "\n";
        }

        freeaddrinfo(res);
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM