How can I resolve a host IP address, given a URL in Visual C++?
To do this in Chrome, simply open up the DevTools, navigate to the Network tab and select the site's HTML doc. You should then see the IP address associated with that URL under Headers > General > Remote Address.
DNS keeps the record of all domain names and the associated IP addresses. When you type in a URL in your browser, DNS resolves the domain name into an IP address. In other words, DNS is a service that maps domain names to corresponding IP addresses.
Using the host Command The host command is a DNS lookup utility used to convert domain names to IP addresses and reverse IP lookup.
host name resolution is attempted using the HOSTS file. If the host name could not be resolved to an IP address using the HOSTS file, the DNS server is used. The request is transmitted to the local DNS server to perform a lookup of the name in its database and resolve it to an IP address.
I'm not sure if there is a specific C++ class to do host name lookups, but you can always resort to plain C for such things. Here's my version which compiles and runs on Linux, Mac OS X, and Windows.
#include <stdio.h>
#ifdef _WIN32
# include "winsock.h"
#else
# include <netdb.h>
# include <arpa/inet.h>
#endif
static void initialise(void)
{
#ifdef _WIN32
WSADATA data;
if (WSAStartup (MAKEWORD(1, 1), &data) != 0)
{
fputs ("Could not initialise Winsock.\n", stderr);
exit (1);
}
#endif
}
static void uninitialise (void)
{
#ifdef _WIN32
WSACleanup ();
#endif
}
int main (int argc, char *argv[])
{
struct hostent *he;
if (argc == 1)
return -1;
initialise();
he = gethostbyname (argv[1]);
if (he == NULL)
{
switch (h_errno)
{
case HOST_NOT_FOUND:
fputs ("The host was not found.\n", stderr);
break;
case NO_ADDRESS:
fputs ("The name is valid but it has no address.\n", stderr);
break;
case NO_RECOVERY:
fputs ("A non-recoverable name server error occurred.\n", stderr);
break;
case TRY_AGAIN:
fputs ("The name server is temporarily unavailable.", stderr);
break;
}
}
else
{
puts (inet_ntoa (*((struct in_addr *) he->h_addr_list[0])));
}
uninitialise ();
return he != NULL;
}
Once compiled, provide the host name as an argument:
$ ./a.out stackoverflow.com
69.59.196.211
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With