简体   繁体   中英

Get IP from URL (C++)

How can I get the IP-address from a domain name with the top level domain name? In this example get the IP of google.com. And if possible in IPv6 in the correct format.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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